You must Sign In to post a response.
  • Category: XML

    How to re-arrange the nodes in XML using C#.net

    Hi Everybody,

    My XML file is like below.


    <?xml version="1.0" encoding="utf-8" ?>
    <root>
    <a>
    <a1></a1>
    <a2></a2>
    <a3>
    <b>
    <b1>
    <c></c>
    </b1>
    <b2></b2>
    <b3></b3>
    </b>
    </a3>
    <a4></a4>
    </a>
    </root>


    In parent under a3 node I have Sub roots then need to remove a3 under "a" root and create parent root as b after "a" root.

    My expected output xml in below format.


    <?xml version="1.0" encoding="utf-8" ?>
    <root>
    <a>
    <a1></a1>
    <a2></a2>

    <a4></a4>
    </a>

    <b>

    <b2></b2>
    <b3></b3>
    </b>

    <c></c>

    </root>


    How to do this. Can any one give me some suggestion to perform this action.

    Regards,
    Naveen
  • #743748
    The Algorithm that you have to follow is for the nodes if there are any children it should be removed , I mean at any point of time you need to have only one parent and child relationship?
    You can this using XLinq.is it fixed descender or the nodes will change everytime? if you know the Descendants then you can find the descendants
    XDocument doc = XDocument.Load(@"yourXML.xml");
    var deleteQuery = from r in doc.Descendants("a") where r.Element("b").Value == b select r;
    foreach (var qry in deleteQuery)
    {
    qry.Element("b").Remove();
    }
    doc.Save(@"youxml.xml");


  • Sign In to post your comments