简体   繁体   中英

Adding Xml Attribute to All elements except root Node

I am trying to add new attribute to my xml files in c#. my xml file format is shown below:

<Root MessageOfRoot="Welcome to Xml">
    <Header Size="36">
        <Parameter Name="ID" Index="0" Value="23" />
        <Parameter Name="Name" Index="4" Value="Uncle Bob" />
        <Parameter Name="Number" Index="8" Value="4" />
    </Header>
    <Body Size="0">
        <Parameter Index="0" UnitNumber="0" Name="UnitBarcode" Type="Integer" />
        <Parameter Index="4" PromotionId="0" Name="PromotionalUnit" Type="Integer" />
    </Body>
</Root>

I want to add new attribute my xml file which should be like:

<Root MessageOfRoot="Welcome to Xml">
    <Header Size="36" NewAttr="1">
        <Parameter Name="ID" Index="0" Value="23" NewAttr="1"/>
        <Parameter Name="Name" Index="4" Value="Uncle Bob" NewAttr="1"/>
        <Parameter Name="Number" Index="8" Value="4" NewAttr="1"/>
    </Header>
    <Body Size="0" NewAttr="1">
        <Parameter Index="0" UnitNumber="0" Name="UnitBarcode" Type="Integer" NewAttr="1"/>
        <Parameter Index="4" PromotionId="0" Name="PromotionalUnit" Type="Integer" NewAttr="1"/>
    </Body>
</Root>

To do that i write the following code but i am having problem with adding newAttr to all nodes. How can i add NewAttr to my new xml file?

XmlDocument doc = new XmlDocument();
doc.Load("Path of xml");
XmlAttribute NewAttr = doc.CreateAttribute("NewAttr ");
countAttr.Value = "1";
XmlWriter writer = XmlWriter.Create("output.xml", settings);

You can use the following command to load the XML file:

XDocument doc = XDocument.Load(@"C:\Users\myUser\myFile.xml");

Then you can invoke a function that recursively accesses all nodes of the XML starting from the children nodes of the Root element:

AddNewAttribute(doc.Root.Elements());

The function can be like so:

public static void AddNewAttribute(IEnumerable<XElement> elements)
{
    foreach (XElement elm in elements)
    {
        elm.Add(new XAttribute("newAttr", 1));
        AddNewAttribute(elm.Elements());
    }
}

Finally, you can save the XML back to the original file using:

doc.Save(@"C:\Users\myUser\myFile.xml");

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