xml - linq 到 xml : how to select the value from elements

标签 xml linq

我需要返回元素列表 <AssetText> .我下面的查询只返回第一个 AssetText .非常感谢任何想法。

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>

最佳答案

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");

关于xml - linq 到 xml : how to select the value from elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356091/

相关文章:

c# - Linq to SQL 多条件 where 子句

c# - 使用 Linq + group by 查询容器?

python - 使用元素树 findall 解析 XML 命名空间

php - SimpleXML 获取节点值

c# - 一个用于连接具有相同接口(interface)的两个不同对象列表的衬垫

c# - 在linq中获取多个不同的分组值

c# - 我应该在 LINQ 中使用两次 OrderByDescending 吗?

java - 如何在 Android 中查找所有资源 ID

java - 使用 html 更改 XML 值

java - JAXB2.0 -XJC编译问题