简体   繁体   中英

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#

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.
  • 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()

The following code shows the changes:

XDocument doc = XDocument.Load(@"F:\XML\023615123651.xml");
foreach(var el in doc.Descendants())
  el.SetAttributeValue("Type", "object");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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