user2029200
user2029200

Reputation: 103

Swapping nodes in xmlNodeList C#

Assuming having the following xml

<test>
    <step>
        <var name="name1" />
        <var name="name2" />
    </step>

    <step>
        <var name="name3" />
        <var name="name4" />
    </step>

    <step>
        <var name="name5" />
        <var name="name6" />
    </step>

</test>

I m using XmlNodeList, seperated by "step". Is there a way to swap or replace a step directly in the xmlnodelist?

Need to make it like this:

<test>
    <step>
        <var name="name3" />
        <var name="name4" />
    </step>

    <step>
        <var name="name1" />
        <var name="name2" />
    </step>

    <step>
        <var name="name5" />
        <var name="name6" />
    </step>

</test>

Upvotes: 0

Views: 1818

Answers (3)

user2029200
user2029200

Reputation: 103

Finally managed to do it, here is the code:

        XmlDocument xml;
        XmlNodeList xmlList;

        xml = new XmlDocument();
        xml.Load(path);

        xmlList = xml.GetElementsByTagName("step");

        XmlNode refNode = xmlList[1];

        XmlNode newNode = xmlList[0];

        xml.DocumentElement.InsertAfter(newNode, refNode);

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56707

The order of the nodes in an XML file does not necessarily have to be kept when the XML file is read. For example, if your file looks like this:

<xmlcontent>
    <node value="Hello" />
    <node value="World" />
</xmlcontent>

The XML read may return the nodes like this:

<xmlcontent>
    <node value="World" />
    <node value="Hello" />
</xmlcontent>

To apply something like an "order" to XML nodes, you need to add an attribute you can sort by, like

<xmlcontent>
    <node index="1" value="Hello" />
    <node index="2" value="World" />
</xmlcontent>

In that case, "swapping" two elements would come down to swapping the index values.

Upvotes: 1

cvraman
cvraman

Reputation: 1697

You can use XDocument class instead of XMLDocument. This will swap the var nodes name3 with name6.

using System.Linq;
using System.Xml.Linq;
class Test
{

    static void Main()
    {
        XDocument document = XDocument.Load("test.xml");
        Swap("name3", "name6", document);
        document.Save("test.xml");
    }

    static void Swap(string nameOne, string nameTwo, XDocument document)
    {
        var nameOneNode = document.Descendants("var").FirstOrDefault(p => p.Attribute("name").Value == nameOne);
        var nameTwoNode = document.Descendants("var").FirstOrDefault(p => p.Attribute("name").Value == nameTwo);
        nameOneNode.Attribute("name").Value = nameTwo;
        nameTwoNode.Attribute("name").Value = nameOne;
    }
}

Upvotes: 3

Related Questions