2013-04-23 184 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