【问题标题】:How can i get Mulitiple subnode values using Linq to xml?如何使用 Linq to xml 获取多个子节点值?
【发布时间】:2012-09-12 11:55:06
【问题描述】:

我得到了 xml 中的 Web 服务响应。

<Items>
  <Item>
    <SmallImage>
      <Url>http://xxx<url>
      <height></height>
      <weight></weight>
    </SmallImage>
    <LargeImage>
      <Url>http://xxx<url>
      <height></height>
      <weight></weight>
    </LargeImage>
    <ItemAttributes>
      <Binding>Apparel</Binding>
      <Brand>Calvin Klein Jeans</Brand>
      <Department>mens</Department>
      <Title>Calvin Klein Jeans Men's Rusted Antique Skinny Jean</Title>
    </ItemAttributes>
    <SimilarProducts>
       <SimilarProduct>
         <ASIN>B0018QK10E</ASIN>
         <Title>New Balance Men's M574 Sneaker</Title>
       </SimilarProduct>
    </SimilarProducts>
  </Item>
</Items>

在这里,我只需要显示标题。 Items->Item->ItemAttributes->Title

我试过这样。

           #region Product Title
        var Title = xd.Descendants(ns + "Item").Select(b => new
        {
            PTitle = b.Element(ns + "ItemAttributes").Element(ns + "Title").Value
        }).ToList();
        #endregion 

但它返回 Object null。请让我知道您需要更多信息。 提前致谢。

【问题讨论】:

  • 看这里如何使用命名空间stackoverflow.com/questions/604680/…
  • @AmiramKorach 我试过这样:XName xn=XName.Get("Title","webservices.amazon.com/AWSECommerceService/2005-10-05"); var title=from ft in xd.Descendants(xn) select new { Ptitle=ft .Element("Title").Value }; 但什么都没有。,
  • 您需要将其添加到对 Descendants 和 Element 的每次调用中。稍微搜索一下并学习。
  • @AmiramKorach 我自己解决了。,谢谢。,

标签: linq linq-to-sql linq-to-xml linq-to-objects


【解决方案1】:

您需要正确的 xml 命名空间名称来搜索 LINQ 查询中的元素。

可以获取xmlnamespace:

XNamespace ns = xd.Root.Attribute("xmlns").Value;

并在您的 LINQ 查询中使用 ns。

或者试试,

var Items = xd.Descendants().Where(a => a.Name.LocalName == "Item");
var ItemAttributes = Items.Descendants().Where(b => b.Name.LocalName == "ItemAttributes");
List<string> Titles = ItemAttributes.Descendants().Where(c => c.Name.LocalName == "Title").Select(o => o.Value).ToList<string>();

【讨论】:

    【解决方案2】:

    解决方案:

    var Title = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(BTitle => BTitle.Elements(ns + "ItemAttributes").Select(BTitle1 => (string)BTitle1.Element(ns + "Title")).FirstOrDefault() ?? "Null").ToList();
    

    【讨论】:

    • 想为您的解决方案添加一些评论?它是如何工作的?它如何回答 OP 问题?
    • 你在问什么。你问的是OP的意思吗?检查this meta link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2012-09-06
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多