0

我有一个 xml 文件,我想反转一些节点,然后我想保存结果。我使用了 XDocumnt 并在其上使用了 revese 函数,它正确地反转了,但之后我不知道如何保存文件。像下面这样的原始文件

    <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>

我需要将其反转如下:

    <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>

之后,我想将其保存到新文件中。

谁能帮我?

4

1 回答 1

0

我发现我应该使用ReplaceNode函数替换反转节点然后保存文件但反转函数不反转文件内的节点,不它只是返回新的反转值,我应该手动替换它们如下

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");
于 2018-08-06T10:43:38.937 回答