C# 如何使用C向xml节点添加新的计数器属性#
我正在研究如何向xml节点添加一个新属性C# 如何使用C向xml节点添加新的计数器属性#,c#,xml,xpath,C#,Xml,Xpath,我正在研究如何向xml节点添加一个新属性count,将其作为进一步解析的id 我的XML: <objects> <object name="Ford Fuigo" type="Car"> <properties> ... </properties> </object> <object name="Renault Clio" type
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>
...
...
...
基于XML创建XmlDocument
,然后使用选择SingleNode
查找节点并对其进行更改
您还可以像下面这样使用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");
谢谢,但由于我在xml层次结构中有所需的元素,root.elements(“对象”)不起作用,root.subjects(“对象”)起作用。