【问题标题】:find the node value in xDocument在 xDocument 中查找节点值
【发布时间】:2015-03-12 09:06:12
【问题描述】:

我无法获得价值。

如何获得StatusDescription 值?请告诉我。

<WebServiceResponse xmlns="ws.abc.com">
  <SubscriptionInfo xmlns="ws.abc.com">
    <LicenseStatusCode>0</LicenseStatusCode>
    <Amount>0</Amount>
  </SubscriptionInfo>
  <VerificationResponse xmlns="www.abc.com">
    <VerificationResult>
      <ServiceStatus>
        <StatusNbr>304</StatusNbr>
        <StatusDescription>Address Not Found</StatusDescription>
      </ServiceStatus>
      <ServiceResult />
    </VerificationResult>
  </VerificationResponse>
</WebServiceResponse>

【问题讨论】:

    标签: asp.net-mvc-4 c#-4.0 model-view-controller


    【解决方案1】:

    您的 xml 包含命名空间,使用 XDocument 您可以通过以下方式获得所需的节点值:

     XDocument doc = XDocument.Parse(xml);
    
     XNamespace xmlNamespace = "www.abc.com";
     var ResultNode = from a in doc.Descendants(xmlNamespace + "VerificationResponse").Descendants(xmlNamespace + "StatusDescription")
                      select a.Value;
    

    WORKING DOTNET FIDDLE

    【讨论】:

      【解决方案2】:

      你可以使用这样的东西(使用 Linq-to-XML)

      // define the XML namespace of the <VerificationResponse> node and down
      XNamespace wwwabc = "www.abc.com";
      
      // parse your XML into a XDocument
      XDocument xdoc = XDocument.Parse(your-xml-input);
      
      // get the <StatusDescription> node(s) from the XDocument
      // here I'm assuming there's only one such node, so I'm using
      // the .FirstOrDefault() method to fetch it
      var statusDescriptionNode = xdoc.Descendants(wwwabc + "StatusDescription").FirstOrDefault();
      
      // if we found a first such node
      if (statusDescriptionNode != null)
      {
          string statusDescription = statusDescriptionNode.Value;
      }
      

      当然,如果这是一个非常庞大且复杂的 XML,那么 .Descendants() 调用可能效率不高(它只是在整个 XML 文档中搜索该命名空间 + 节点名称的节点)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多