[英]How to add attribute to all child nodes in xml using C#
I am having XML, I want to add an attribute to all child node of xml document using C# 我正在使用XML,我想使用C#向XML文档的所有子节点添加属性
After review so many posts and blogs , confusing me 经过审查这么多的帖子和博客,使我感到困惑
<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>
Convert like : 像这样转换:
<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>
I got this solutions 我有这个解决方案
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");
}
Based on your answer , I'd propose the following changes: 根据您的回答 ,我建议进行以下更改:
document.Root.Descendants()
to document.Descendants()
document.Root.Descendants()
更改为document.Descendants()
The following code shows the changes: 以下代码显示了更改:
XDocument doc = XDocument.Load(@"F:\XML\023615123651.xml");
foreach(var el in doc.Descendants())
el.SetAttributeValue("Type", "object");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.