我正在寻找如何向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>
答案 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");