2008-12-10 79 views
2

我需要返回元素列表<AssetText>。我的查詢僅返回第一個AssetText。任何想法非常感謝。linq to xml:如何從元素中選擇值

var q = from c in xDoc.Descendants("Product") 
     where (int) c.Element("ProductView").Element("ViewId") == 44 
     select (string) c.Element("ProductView").Element("AssetText").Element("Text"); 

 

<Product> 
    <ProductView> 
    <ViewId>44</ViewId> 
    <AssetText> 
     <Text>my first Asset Text</Text> 
    </AssetText> 
    <AssetText> 
     <Text>my second Asset Text</Text> 
    </AssetText> 
    </ProductView> 
    <ProductView> 
    <ViewId>45</ViewId> 
    <AssetText> 
     <Text>my third Asset Text</Text> 
    </AssetText> 
    </ProductView> 
</Product> 

回答

8

變化Element("AssetText")Elements("AssetText")得到所有的AssetText元素。請注意,您需要更改查詢的其餘部分,否則只有當第一個ProductView的ViewId爲44時纔會匹配。我建議您使用第二個「from」子句:

var q = from c in xDoc.Descendants("Product") 
     from view in c.Elements("ProductView") 
     where (int) view.Element("ViewId") == 44 
     from assetText in view.Elements("AssetText") 
     select assetText.Element("Text");