2012-09-12 52 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