2012-02-27 152 views
0

我想使用XElement來找出一個孩子的父節點。看下面的例子。這是我的數據:如何找出孩子的父母?

<Data> 
    <Description>King</Description> 
    <Data> 
     <Description>Mike</Description> 
     <Data id="GUID1" Description="THIS IS A TEST" /> 
    </Data> 
    <Data> 
     <Description>David</Description> 
     <Data id="GUID2" Description="THIS IS A TEST" /> 
     <Data id="GUID3" Description="THIS IS A TEST" /> 
    </Data> 
    <Data id="GUID4" Description="THIS IS A TEST" /> 
</Data> 

所以父母(國王)有兩個孩子邁克和大衛。我想要找出誰是「大衛」的家長,我怎麼能找到這個?

這裏是我下面的代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    var s = 
    @"<Data> 
      <Description>King</Description> 
      <Data> 
      <Description>Mike</Description> 
      <Data id=""GUID1"" Description=""THIS IS A TEST"" /> 
      </Data> 
      <Data> 
      <Description>David</Description> 
      <Data id=""GUID2"" Description=""THIS IS A TEST"" /> 
      <Data id=""GUID3"" Description=""THIS IS A TEST"" /> 
      </Data> 
      <Data id=""GUID4"" Description=""THIS IS A TEST"" /> 
     </Data>"; 

    var doc = XElement.Load(new StringReader(s)); 

    var result = (from data in doc.Descendants("Data") 
        where (string)data.Attribute("id") != null 
        select new 
        { 
         Id = data.Attribute("id").Value, 
         Decription = data.Attribute("Description").Value, 
         Child = data.Parent.Element("Description").Value, 
         Parent = data.Parent.Parent.Value **** THIS LINE **** 
        }); 

    foreach (var element in result) 
    { 
     Console.WriteLine("{0} {1}", element.Id, element.Decription); 
    } 
} 

我什麼都試過,但沒有運氣。我一直在收到data.Parent.Parent.Value ="KingMikeDavid"的全部結果,這是錯誤的。如何在沒有孩子的情況下返回「國王」?

回答

3

data.Parent.Parent是指整個Data元素,其值是其後代的組合值。你需要它的Description孩子的值:

Parent = data.Parent.Parent == null ? null : 
    data.Parent.Parent.Element("Description").Value 
+0

抱歉,我忘了添加另一行中的XML <數據ID =「」 GUID4「」說明=「」這是一個測試「」 />請參閱更新版本。這會拋出一個null執行選項? – user929153 2012-02-27 13:36:03

+0

但是這個元素是最頂層的數據元素的一個孩子,它屬於國王,可以這麼說,沒有父母......我編輯了這個案例的答案。 – user1096188 2012-02-27 13:45:33

+0

謝謝你工作。 :-)花了很多時間在這.. – user929153 2012-02-27 13:47:38