2012-05-01 173 views
0

我有這樣的xml。如何從屬性值中選擇並遍歷XML xElement節點?

<?xml version="1.0" encoding="utf-8" ?> 
<Category ID="1" AICategoryName="Schedule K: Income/Loss" Taxonomy="K"> 
    <Level1 ID="11965" Name="Guaranteed payments" Taxonomy="4"> 
     <Level2 ID="27058" Name="Gtd Pmts(trade/bus) to Sch. M-1" Taxonomy="1"> 
     </Level2> 

     <Level2 ID="27059" Name="Gtd Pmts not to Sch. M-1" Taxonomy="2">  
     </Level2> 
    </Level1> 

    <Level1 ID="119652" Name="2Guaranteed payments" Taxonomy="4"> 
     <Level2 ID="227058" Name="2Gtd Pmts(trade/bus) to Sch. M-1" Taxonomy="1"> 
     </Level2> 

     <Level2 ID="227059" Name="2Gtd Pmts not to Sch. M-1" Taxonomy="2">  
     </Level2> 
    </Level1> 
</Category> 

我想通過提供父節點attribite ID獲取父節點下的子節點。

例如,如果我提供Level1和11965,我應該得到所有2級節點及其名稱和ID。

我已經試過這個代碼。

XDocument xd = XDocument.Load(xmlPath); 

     var xl = from xml2 in xd.Descendants("Level1") 
       where xml2.Parent.Attribute("ID").Value == parentNode.ID 
       select xml2; 

但代碼yeilds沒有結果。也一旦我得到xl,我如何遍歷它來獲取子節點名稱和ID?

+0

'xd.Descendants( 「1級」)'選擇該_are_ 1級,沒有後代_of_ Level' –

回答

2
XDocument xd = XDocument.Load(xmlPath); 
var nodes = (from n in xd.Root.Desendants(tagName/*Level1*/) where n.Attribute("Id").Value == "idValue" select n.Elements()).single().select(n=>{return new{ 
Id = n.attribute("Id").value, 
Name = n.attribute("Name").value, 
Taxonomy = n.attribute("Taxonomy").value 
}}); 

如果所請求的標籤名始終爲「Level1」,並且xml結構已修復,那麼您也可以更改上面的代碼。

XDocument xd = XDocument.Load(xmlPath); 
var nodes = (from n in xd.Root.Elements("Level1") where n.Attribute("Id").Value == "idValue" select n.Elements()).single().select(n=>{return new{ 
    Id = n.attribute("Id").value, 
    Name = n.attribute("Name").value, 
    Taxonomy = n.attribute("Taxonomy").value 
    }}); 
+0

你是對的元素,單()是更好地使用,比第一() –

+0

thankx爲給予好評..這個代碼也解決了你的問題劑量嗎? –

+0

這就是我upvoted :) –

1

LINQ(假設你總是對提供的ID單1級節點):

XDocument xd = XDocument.Load(xmlPath); 
int parentId = 119652; 
var nodes = (from level1 in xd.Descendants("Level1") 
      where ((int)level1.Attribute("ID")) == parentId 
      select level1.Descendants("Level2")) 
      .Single() 
      .Select(level2 => new { ID = (int)level2.Attribute("ID"), 
            Name = level2.Attribute("Name").Value }); 

迭代

foreach (var level2 in nodes) 
    // level2.Name and level2.ID 

如果有可能的,1級節點不存在提供的ID或你有幾個1級節點與相同的ID:

int parentId = 119652; 
XDocument xd = XDocument.Load(xmlPath); 
var query = xd.Descendants("Level1") 
       .Where(level1 => ((int)level1.Attribute("ID")) == parentId) 
       .SelectMany(level1 => level1.Descendants("Level2")) 
       .Select(level2 => new { ID = (int)level2.Attribute("ID"), 
             Name = level2.Attribute("Name").Value }); 

foreach (var level2 in query) 
    // level2.Name and level2.ID