2013-04-23 185 views
0

以下是我從web服務生成的響應。 我想這樣做,我只需要這個響應的PresentationElements節點。 任何幫助我如何實現這個查詢?從xml響應中提取節點

<?xml version="1.0"?> 
<GetContentResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <ExtensionData /> 
    <GetContentResult> 
    <ExtensionData /> 
    <Code>0</Code> 
    <Value>Success</Value> 
    </GetContentResult> 
    <PresentationElements> 
    <PresentationElement> 
     <ExtensionData /> 
     <ContentReference>Product View Pack</ContentReference> 
     <ID>SHOPPING_ELEMENT:10400044</ID> 
     <Name>View Pack PE</Name> 
     <PresentationContents> 
     <PresentationContent> 
      <ExtensionData /> 
      <Content>View Pack</Content> 
      <ContentType>TEXT</ContentType> 
      <Language>ENGLISH</Language> 
      <Medium>COMPUTER_BROWSER</Medium> 
      <Name>Name</Name> 
     </PresentationContent> 
     <PresentationContent> 
      <ExtensionData /> 
      <Content>Have more control of your home's security and lighting with View Pack from XFINITY Home.</Content> 
      <ContentType>TEXT</ContentType> 
      <Language>ENGLISH</Language> 
      <Medium>COMPUTER_BROWSER</Medium> 
      <Name>Description</Name> 
     </PresentationContent> 
     <PresentationContent> 
      <ExtensionData /> 
      <Content>/images/shopping/devices/xh/view-pack-2.jpg</Content> 
      <ContentType>TEXT</ContentType> 
      <Language>ENGLISH</Language> 
      <Medium>COMPUTER_BROWSER</Medium> 
      <Name>Image</Name> 
     </PresentationContent> 
     <PresentationContent> 
      <ExtensionData /> 
      <Content>The View Pack includes: 
2 Lighting/Appliance Controllers 
2 Indoor/Outdoor Cameras</Content> 
      <ContentType>TEXT</ContentType> 
      <Language>ENGLISH</Language> 
      <Medium>COMPUTER_BROWSER</Medium> 
      <Name>Feature1</Name> 
     </PresentationContent> 
     </PresentationContents> 
    </PresentationElement> 
    </PresentationElements> 
</GetContentResponse> 

回答

1

很容易,你有沒有嘗試過:

XDocument xml = XDocument.Load("... xml"); 
var nodes = (from n in xml.Descendants("PresentationElements") 
         select n).ToList(); 

你也使用類似項目中的各個節點以匿名類型:

select new 
{ 
    ContentReference = (string)n.Element("ContentReference").Value, 
    .... etc 
} 
+0

已嘗試上述解決方案..但它返回一個IEnumerable。這會導致問題。可能是我沒有投它.ToList() – 2013-04-23 09:31:07

+0

是的,你必須通過調用'ToList()'或'ToArray()'來枚舉它。 – DGibbs 2013-04-23 09:32:04

3

您可以使用System.Xml.Linq.XDocument

//Initialize the XDocument 
XDocument doc = XDocument.Parse(yourString); 

//your query 
var desiredNodes = doc.Descendants("PresentationElements"); 
+2

@Downvoter如果看到您的評論將很高興。 – 2013-04-23 09:19:11

+0

也許downvoted,因爲它不是一個文件,但從服務的響應;但我只能猜測。 – 2013-04-23 09:26:41

+0

經典解決方案+1 :) – 2013-04-23 09:33:31

5

您可以使用XPath擴展

var xdoc = XDocument.Parse(response); 
XElement presentations = xdoc.XPathSelectElement("//PresentationElements"); 
+2

+1不同的解決方案。 – 2013-04-23 09:32:20