更改XmlDocument中元素的顺序

时间:2013-07-06 15:38:56

标签: c# xml xmldocument

这里是xml的例子:

<root>
<something1></something1>
<something2></something2>
<something3></something3>
<important>
<some1>123_random_number</some1><some2>ASD</some2>
</important>
<important>
<some1>456_random_number</some1><some2>FGH</some2>
</important>
<important>
<some1>789_random_number</some1><some2>JKL</some2>
</important>
</root>

我需要改变元素的顺序,得到像这样的xml文档:

<root>
<something1></something1>
<something2></something2>
<something3></something3>
<important>
<some1>789_random_number</some1><some2>JKL</some2>
</important>
<important>
<some1>456_random_number</some1><some2>FGH</some2>
</important>
<important>
<some1>123_random_number</some1><some2>ASD</some2>
</important>
</root>

有人能帮助我吗? 提前致谢, P

1 个答案:

答案 0 :(得分:0)

这很简单,但我是初学者:) 这是答案:

XmlReader reader = XmlReader.Create(@"dataIn.xml");
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNodeList elem = doc.GetElementsByTagName("important");

List<string> originalOrder = new List<string>();

foreach (XmlNode tag in elem)
  {
    originalOrder.Add(tag.InnerXml);
  }

int numberOfNodes = elem.Count;

for (int i = 0; i < numberOfNodes; i++) {
    elem[i].InnerXml = order[order.Count - 1 - i];
  }
doc.Save(@"dataOut.xml");