如何使用C#向xml节点添加新的计数器属性

时间:2014-04-17 10:00:20

标签: c# xml xpath

我正在寻找如何向xml节点添加新属性count以将其作为进一步解析的id。

我的XML:

<objects>
    <object name="Ford Fuigo" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object name="Renault Clio" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object name="Evico Star" type="Bus">
          <properties>
           ...      
           </properties>
    </object>
</objects>

我希望有一个像这样的新属性:

<objects>
    <object count ="1" name="Ford Fuigo" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object count ="2" name="Renault Clio" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object count ="3" name="Evico Star" type="Bus">
          <properties>
           ...      
           </properties>
    </object>
</objects>

1 个答案:

答案 0 :(得分:2)

根据您的XML创建XmlDocument,然后使用SelectSingleNode查找节点并进行更改

http://msdn.microsoft.com/en-us/library/fb63z0tw.aspx

你也可以使用XElement,如下所示:

XElement root = XElement.Load("input.xml");
int counter = 0;
foreach (var obj in root.Descendants("object"))
{
    obj.Add(new XAttribute("count", ++counter));
}

root.Save("output.xml");