2008-12-04 101 views
1

問候!LINQ to XML新手問題:返回節點值和正負值

我有一些這樣的XML:

<Root> 
    <AlphaSection> 
    . 
    . 
    . 
    </AlphaSection> 

    <BetaSection> 
     <Choices> 
      <SetA> 
       <Choice id="choice1"> 
        <Title>Choice 1 Title</Title> 
        <Body>Choice 1 Body</Body> 
       </Choice> 
       <Choice id="choice2"> 
        <Title>Choice 2 Title</Title> 
        <Body>Choice 2 Body</Body>     
       </Choice> 
      </SetA> 
      <SetB> 
       <Choice id="choice3"> 
        <Title>Choice 3 Title</Title> 
        <Body>Choice 3 Body</Body> 
       </Choice> 
       <Choice id="choice4"> 
        <Title>Choice 4 Title</Title> 
        <Body>Choice 4 Body</Body>     
       </Choice> 
      </SetB> 
     </Choices> 
    </BetaSection> 

    <GammaSection> 
    . 
    . 
    . 
    </GammaSection> 
</Root> 

我目前在做以下檢索每個選擇的ID:

var choiceList = myXDoc.Root 
         .Element("BetaSection") 
         .Descendants("Choice") 
         .Select(element => new 
           { 
            ID = element.Attribute("id").Value, 
            // Title = ? 
            // Body = ? 
           }); 

我也想獲得值每個選擇的標題和正文子節點。我會怎麼做呢?謝謝。

回答

1
element => new { 
       ID = element.Attribute("id").Value, 
       Title = element.Element("Title").Value, 
       Body = element.Element("Body").Value 
       }); 
+0

現在我覺得愚蠢的:)謝謝。 – Bullines 2008-12-04 01:13:19

0

另外的XElement提供了一系列的類型轉換重載的,所以你不喜歡的東西......

element => new { 
       ID = (string)element.Attribute("id"), 
       title = (string)element.Element("Title"), 
       Body = (string)element.Element("Body") 
       });