XML排序出现异常



我正在LINQ中尝试根据元素的属性对XML文件中的元素进行排序:

public void SortXml()
{
    XDocument doc = XDocument.Load(filename);
    XDocument datatemp = new XDocument(doc);
    doc.Descendants("Thing").Remove();
    var module = datatemp.Descendants("Thing").OrderBy(x => 
        (int)int.Parse(x.Attribute("ID").Value));
    doc.Element("Thing").Add(module);
    doc.Save(filename);
}

XML:

<Entry>
  <Properties>
    <Thungs Count="2">
      <Thing ID="1">
        <thing1 num="8" />
        <thing1 num="16" />
      </Thing>
      <Thing ID="31">
        <thing1 num="8" />
        <thing1 num="16" />
      </Thing>
    </Thungs>
  </Properties>
</Entry>

但在doc.Element("Thing").Add(module);行中,我得到了一个NullReferenceException。怎么了?

doc.Element("Thing")将返回null,因为没有名为"Thing"的元素:doc.Descendants("Thing").Remove();调用已将它们全部删除。即使没有,XElementElement方法也不会查看间接子体,因此您需要提供正确的元素名称链,以指向要修改的元素。

你是想写吗

doc.Element("Entry").Element("Properties").Element("Thungs").Add(module);

如果要简化它,为什么不一直进行呢?

XDocument doc = XDocument.Load(filename);
var ordered = doc.Descendants("Thing")
                 .OrderBy(thing => thing.Attribute("ID").Value)
                 .ToList(); // force evaluation
doc.Descendants("Thing").Remove();
doc.Descendants("Thungs").Single().Add(ordered);
doc.Save(filename);

您甚至不需要创建两个XDocument对象:

        XDocument doc = XDocument.Load(filename);
        var query = from things in doc.Descendants("Thing")
                    orderby things.Attribute("ID").Value
                    select things;
        var orderedThings = query.ToList<XElement>();
        doc.Descendants("Thing").Remove();
        doc.Descendants("Thungs").First().Add(orderedThings);
        doc.Save(filename);

编辑:如果你知道XML模式中的"路径",最好使用dasblinkenlight建议:

    doc.Element("Entry").Element("Properties").Element("Thungs").Add(orderedThings);

而不是CCD_ 10线。

最新更新