如何使用Linq to xml获取多个子节点值?

如何使用Linq to xml获取多个子节点值?,linq,linq-to-sql,linq-to-xml,linq-to-objects,Linq,Linq To Sql,Linq To Xml,Linq To Objects,我得到了xml格式的Webservice响应 <Items> <Item> <SmallImage> <Url>http://xxx<url> <height></height> <weight></weight> </SmallImage> <LargeImage> <Url>

我得到了xml格式的Webservice响应

<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>
但它返回objectnull。请告诉我您需要更多信息。
提前感谢。

您需要正确的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>();
var Items=xd.subjects()。其中(a=>a.Name.LocalName==“Item”);
var itemtattributes=Items.subjects()。其中(b=>b.Name.LocalName==“itemtattributes”);
List Titles=itemtattributes.subjects()。其中(c=>c.Name.LocalName==“Title”)。选择(o=>o.Value)。ToList();
解决方案:

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

看看这里如何使用名称空间@AmiramKorach,我是这样尝试的:XName xn=XName.Get(“Title”);var Title=from ft in xd.subjections(xn)选择新的{Ptitle=ft.Element(“Title”).Value};但没什么。您需要将其添加到对子体和元素的每次调用中。对其进行一点搜索并学习。@AmiramKorach我自己解决了这个问题,谢谢。是否要为您的解决方案添加一些注释?它是如何工作的?它如何回答OP问题?您在问什么。您想了解OP的含义吗?请检查
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();