从xml响应中提取节点

时间:2013-04-23 09:13:30

标签: c# xml

以下是我从网络服务生成的回复。 我想这样做,我只想从这个响应PresentationElements节点。 任何帮助我如何实现这个查询?

<?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>

3 个答案:

答案 0 :(得分:5)

您可以使用XPath扩展

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

答案 1 :(得分:3)

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

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

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

答案 2 :(得分: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
}