我正在使用XML, 我想使用C#
为xml文档的所有子节点添加一个属性审核了这么多帖子和博客后,让我感到困惑
<root >
<EncrypteText >vishal sen</EncrypteText>
<Category >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</Category>
<CategoryArray >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</CategoryArray>
<CategoryArray >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</CategoryArray>
</root>
转换为:
<root type="object">
<EncrypteText Type="object">vishal sen</EncrypteText>
<Category Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</Category>
<CategoryArray Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</CategoryArray>
<CategoryArray Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</CategoryArray>
</root>
答案 0 :(得分:0)
我得到了这个解决方案
XmlDocument xml = new XmlDocument();
xml.Load(@"F:\XML\023615123651.xml");
XDocument document = XDocument.Load(new StringReader(xml.DocumentElement.OuterXml));
foreach (XElement node in document.Root.Descendants())
{
node.SetAttributeValue("Type", "object");
}
答案 1 :(得分:0)
根据您的answer,我建议进行以下更改:
document.Root.Descendants()
更改为document.Descendants()
以下代码显示了更改:
XDocument doc = XDocument.Load(@"F:\XML\023615123651.xml");
foreach(var el in doc.Descendants())
el.SetAttributeValue("Type", "object");