Search code examples
c#linq-to-xmlxdoc

How to save xml file after reverse some childs on it


I have an xml file and I want to reverse some nodes and after that I want to save the result. I used XDocumnt and use revese function on it and it reversed correctly but after that I don not know how to save the file. the original file like the follwing

    <root>
  <parent>
    <child>
      <sec>
        <p>
          <my-formula>
            <test id="H1"></test id="H1">
          </my-formula>
          <my-formula>
            <test id="H2"></test id="H2">
          </my-formula>
          <my-formula>
            <test id="H3"></test id="H3">
          </my-formula>
        </p>
      </sec>
      <sec>
        <p>
          <my-formula>
            <test id="H4"></test id="H4">
          </my-formula>
          <my-formula>
            <test id="H5"></test id="H5">
          </my-formula>
          <my-formula>
            <test id="H6"></test id="H6">
          </my-formula>
        </p>
      </sec>
    </child>
  </parent>
</root>

I need to reverse it as the following:

    <root>
  <parent>
    <child>
      <sec>
        <p>
          <my-formula>
            <test id="H6"></test id="H6">
          </my-formula>
          <my-formula>
            <test id="H5"></test id="H5">
          </my-formula>
          <my-formula>
            <test id="H4"></test id="H4">
          </my-formula>
        </p>
      </sec>
      <sec>
        <p>
          <my-formula>
            <test id="H3"></test id="H3">
          </my-formula>
          <my-formula>
            <test id="H2"></test id="H2">
          </my-formula>
          <my-formula>
            <test id="H1"></test id="H1">
          </my-formula>
        </p>
      </sec>
    </child>
  </parent>
</root>

After that I want to save it into new file.

can any one help me?


Solution

  • I find that I should use ReplaceNode function to replace reversed nodes then save the file but reverse function not reverse the nodes inside the file, no it just return the new reversed values and I should replace them manually as the following

    var fileDataXDoc = XDocument.Load("filePath");
                        var elems = fileDataXDoc.Descendants("node_to_be_reversed").Reverse();
    
                        int counter = 0;
    
                        foreach (var xElement in elems)
                        {
                            fileDataXDoc.Descendants("node_to_be_reversed).ElementAt(counter).ReplaceNodes(xElement.Nodes());
                            counter ++;
                        }
    
                        fileDataXDoc.Save("newReversedFile.xml");