使用linq到xml获取空后代



我正在调用一个web服务并使用Webresponse.GetResponseStream来获取下面的XML。

我没有运气使用Linq-to-XML来获得<Item>和<Title>元素。当使用Descendants时,我得到null

谁能建议我可以尝试得到这些元素?

<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
 <Items>
<Request>
  <IsValid>True</IsValid>
  <ItemSearchRequest>
    <ResponseGroup>Small</ResponseGroup>
    <SearchIndex>DVD</SearchIndex>
    <Title>Jaws</Title>
  </ItemSearchRequest>
</Request>
<Item>
  <ASIN>B007STBUIW</ASIN>
  <DetailPageURL>http://www.amazon.com/Jaws-Blu-ray-Digital-Copy-UltraViolet/dp/B007STBUIW%3FSubscriptionId%3DAKIAIR3KWWR37IS5MTBA%26tag%3Dfli048-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB007STBUIW</DetailPageURL>
  <ItemLinks>
    <ItemLink>
      <Description>Technical Details</Description>
      <URL>http://www.amazon.com/Jaws-Blu-ray-Digital-Copy-UltraViolet/dp/tech-data/B007STBUIW%3FSubscriptionId%3DAKIAIR3KWWR37IS5MTBA%26tag%3Dfli048-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007STBUIW</URL>
    </ItemLink>
    <ItemLink>
      <Description>Add To Baby Registry</Description>
      <URL>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB007STBUIW%26SubscriptionId%3DAKIAIR3KWWR37IS5MTBA%26tag%3Dfli048-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007STBUIW</URL>
    </ItemLink>
  </ItemLinks>
  <ItemAttributes>
    <Actor>Roy Scheider</Actor>
    <Creator Role="Writer">Carl Gottlieb</Creator>
    <Director>Steven Spielberg</Director>
    <Title>Jaws (Blu-ray + DVD + Digital Copy + UltraViolet)</Title>
  </ItemAttributes>
</Item>
<Item>
  <ASIN>B008YKB3X6</ASIN>
  <DetailPageURL>http://www.amazon.com/Jaws-Comes-Home-HD/dp/B008YKB3X6%3FSubscriptionId%3DAKIAIR3KWWR37IS5MTBA%26tag%3Dfli048-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB008YKB3X6</DetailPageURL>
  <ItemLinks>
    <ItemLink>
      <Description>Technical Details</Description>
      <URL>http://www.amazon.com/Jaws-Comes-Home-HD/dp/tech-data/B008YKB3X6%3FSubscriptionId%3DAKIAIR3KWWR37IS5MTBA%26tag%3Dfli048-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB008YKB3X6</URL>
    </ItemLink>
  </ItemLinks>
  <ItemAttributes>
    <Creator Role="Producer">Discovery</Creator>
    <ProductGroup>TV Series Episode Video on Demand</ProductGroup>
    <Title>Jaws Comes Home [HD]</Title>
  </ItemAttributes>
</Item>
  </Items>
</ItemSearchResponse>
更新:

谢谢Jim和Kelly,这就是问题所在。现在我可以使用下面的代码来获取这个值:

var itemtitle = doc2.Root.Element(ns + "Items").Elements(ns +     "Item").Elements(ns + "ItemAttributes").Elements(ns + "Title").First();

正如Jim所说,添加名称空间应该可以工作。下面是一个拉出项目的例子。

var xml = XDocument.Parse(xmlstr);
XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2011-08-01";
var items = xml.Root.Element(ns+"Items").Elements(ns+"Item");

相关内容

  • 没有找到相关文章