简体   繁体   English

如何使用C#将属性添加到xml中的所有子节点

[英]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: 根据您的回答 ,我建议进行以下更改:

  • You do not need to load the XML data into an XmlDocument first, but can directly load it into an XDocument using its Load method. 您不需要先将XML数据加载到XmlDocument中,而是可以使用其Load方法将其直接加载到XDocument中。
  • Your code only sets the attribute for the descendants of the root element. 您的代码仅设置根元素后代的属性。 In your sample, you want to add the attribute also to the root element (though it's written as "type" instead of "Type" - I suppose this is a typo). 在您的示例中,您还想将属性添加到根元素(尽管它被写为“类型”而不是“类型”-我想这是一个错字)。 If you want to set it on the root element also, you should change 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.

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