从xml响应中提取节点

本文关键字:提取 节点 响应 xml | 更新日期: 2023-09-27 18:10:31

下面是我从一个webservice生成的响应。我想这样做,我只想从这个响应中得到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>

从xml响应中提取节点

可以使用XPath扩展

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

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

//Initialize the XDocument
XDocument doc = XDocument.Parse(yourString);
//your query
var desiredNodes = doc.Descendants("PresentationElements");

很简单,你试过了吗?

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
}