c# - 根据现有属性的值编辑新属性并将其插入 XML 文件
问题描述
我有一个结构如下的 XML 文件:我读过的所有示例都显示了插入节点,但不是如下所述。
<asset>
<vehicle inUse="true">
<type>sedan</type>
<model>735i</model>
<make>BMW</make>
<year>2017</year>
</vehicle>
<vehicle inUse="true">
<type>sedan</type>
<model>735i</model>
<make>BMW</make>
<year>2016</year>
</vehicle>
</asset>
我想进行批量编辑并在具有最高年份值的现有车辆节点之后插入一个新的车辆节点。所以2017年后
例如上面的代码最终会是这样的:
<asset>
<vehicle inUse="true">
<type>sedan</type>
<model>735i</model>
<make>BMW</make>
<year>2017</year>
</vehicle>
<!-- new node here-->
<vehicle inUse="true">
<type>sedan</type>
<model>735i</model>
<make>BMW</make>
<year>2010</year>
</vehicle>
<vehicle inUse="true">
<type>sedan</type>
<model>735i</model>
<make>BMW</make>
<year>2016</year>
</vehicle>
</asset>
解决方案
您可以将 xml 放入 xmlString 中,您应该搜索最高年份值在哪里,获取它的索引
XElement root = XElement.Parse(xmlString);
var vehicles= root.Descendants("vehicle").ToArray();
var elementBeforeInsert = vehicles[index+1];
elementBeforeInsert.AddBeforeSelf(new XElement("vehicle")); // insert your vehicle here
推荐阅读
- javascript - 如何从用户脚本访问 webpack 模块?
- linux - 磁盘上的可用空间不可用
- azure-functions - 值不能为空。(参数'uriString')
- python - 为每组数据打印一个列表到新行
- snowflake-cloud-data-platform - 将 SQL Server 转换为 Snowflake SQL,如何编写 INSERT 语句以将查询中的数据放入临时表?
- php - 根据所选日期显示期初余额和期末余额 PHP mysqlquery
- r - 如何解释代码“x=numeric(n)”?
- bash - 剪切十六进制地址而不将它们扩展为文本
- spring - Spring 集成 - 使用 afterCommit 表达式将文件写入已处理的目录
- php - 来自 Vue.js App (Axios) 的 2 个同时 API 调用随机失败但在 Postman 中工作