首页 > 解决方案 > 根据现有属性的值编辑新属性并将其插入 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>

标签: c#xml

解决方案


您可以将 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

推荐阅读