2012-09-12 32 views
0

我在xml中获得了Webservice Reponse。如何获得使用Linq到XML的Mulitiple子节点值?

<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->标题

我试过这样。

  #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。请让我知道你需要更多的信息。 在此先感谢。

+0

什么是 “NS” 的价值? –

+0

但它不是在你的xml –

+0

看这里如何使用命名空间http://stackoverflow.com/questions/604680/xdocument-descendants-not-returning-any-elements –

回答

0

您需要正确的xml命名空间名称才能在LINQ Query中搜索Element。

你可以得到XML命名空间:

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

,并在你的LINQ查询中使用纳秒。

或尝试,

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

谢谢我自己解决了它,无论如何我会尽力。 –

0

解决方案:

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

小心添加一些评论到您的解决方案?它是如何工作的?它如何回答OP问题? – Yaroslav

+0

你在问什么。你问的是_OP_的意思吗?检查[此元链接](http://meta.stackexchange.com/questions/79804/whats-stackexchange-ese-for-op) – Yaroslav