2008-12-10 83 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");