简体   繁体   English

如何使用C#将新的counter属性添加到xml节点

[英]How to add new counter attribute to xml nodes with C#

I am looking how to add a new attribute count to xml nodes to have it as an id for further parsing. 我正在寻找如何将新的属性count添加到xml节点,以将其作为进一步解析的id。

My XML: 我的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>

And I want to have a new attribute like this: 我想拥有一个这样的新属性:

<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>

Create XmlDocument based on your XML and then use SelectSingleNode to find nodes and change them 根据您的XML创建XmlDocument ,然后使用SelectSingleNode查找并更改节点

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

you can also use XElement like following: 您还可以像下面这样使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM