2012-07-08 20 views
3

我試圖通過元素的屬性在LINQ的XML文件中的元素進行排序:異常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 。 有什麼不對?

回答

1

如果你打算簡化它,爲什麼不去所有的路?

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); 
4

doc.Element("Thing")將返回null,因爲沒有元素調用"Thing"doc.Descendants("Thing").Remove();調用已將其全部刪除。即使它沒有,XElementElement方法不會看到間接後代,所以喲需要提供正確的元素名稱鏈,以導向您想要修改的元素。

您是不是要找寫

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

我想過這個問題,但沒有,結果是一樣的:NullReferenceException異常( – 2012-07-08 10:17:46

+1

@ user1509821你能試着'doc.Element( 「屬性」)元素( 「Thungs」)添加(模塊);'。? – dasblinkenlight 2012-07-08 10:30:07

+0

謝謝你)它的工作如果 'doc.Element(「Entry」)。doc.Element(「Properties」)。Element(「Thungs」).Add(module);' – 2012-07-08 10:42:53

0

你甚至不需要創建兩個XDocument對象:

編輯:如果你知道內部的 「路徑」 你的XML-Schema使用dasblinkenlight建議將會更好:

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

而不是Descendants("Thungs").First()行。

+0

這更好,非常感謝) – 2012-07-08 10:54:50

+0

'ToList ()'可以寫成'ToList()',因爲類型參數是自動推斷的 – Adam 2012-07-08 10:57:53