2008-11-27 123 views
0

問候!LINQ to XML新手問題:按節點名稱返回節點

如果我有XML像這樣:

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

    <BetaSection> 
     <Choices> 
      <SetA> 
       <Choice id="choice1">Choice One</Choice> 
       <Choice id="choice2">Choice Two</Choice> 
      </SetA> 
      <SetB> 
       <Choice id="choice3">Choice Three</Choice> 
       <Choice id="choice4">Choice Four</Choice> 
      </SetB> 
     </Choices> 
    </BetaSection> 

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

我想獲得的所有選擇項中的「BetaSection」,無論「設置」,他們屬於。我試過以下內容:

var choiceList = from choices in myXDoc.Root.Element("BetaSection").Elements("Choices") 
       where (choices.Name == "Choice") 
       select new 
       { 
        Name = choices.Attribute("id").Value, 
        Data = choice.Value 
       }; 

但無濟於事。我會怎麼做呢?

謝謝。

回答

6

你不需要的where子句在所有 - 你只需要更改的元素來電話的後代:

var choiceList = myXDoc.Root 
         .Element("BetaSection") 
         .Descendants("Choice") 
         .Select(element => new 
           { 
            Name = element.Attribute("id").Value, 
            Data = element.Value; 
           }); 

(我已經從一個查詢表達式轉換它簡單的點標記爲我不要認爲查詢表達式真的對你有幫助。)

+0

它不應該是.Descendants(「選擇」) – 2008-11-27 20:45:04

0

我想寫這個代替。我更喜歡SQL語法,而不是方法的語法,但口味的問題......

class Program 
{ 
    static void Main(string[] args) 
    { 
     String  xml   = @"<Root> 
             <AlphaSection></AlphaSection> 
             <BetaSection> 
              <Choices> 
               <SetA> 
                <Choice id='choice1'>Choice One</Choice> 
                <Choice id='choice2'>Choice Two</Choice> 
               </SetA> 
               <SetB> 
                <Choice id='choice3'>Choice Three</Choice> 
                <Choice id='choice4'>Choice Four</Choice> 
               </SetB> 
              </Choices> 
             </BetaSection> 
             <GammaSection></GammaSection> 
            </Root>"; 
     XElement xmlElement = XElement.Parse(xml); 
     var   choiceList = from c in xmlElement.Descendants().Elements("Choice") 
            select new { 
             Name = c.Attribute("id").Value, 
             Data = c.Value 
            }; 
     foreach (var choice in choiceList) { 
      Console.WriteLine("Name: {0} Data: {1}", choice.Name, choice.Data); 
     } 
    } 
}