2011-10-10 143 views
0

我只是試圖解析SOAP響應並拉出ResponseCodeUnconfirmedReasonCode元素了以下XML的單個節點:麻煩選擇使用XPath

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
    <CoverageResponse xmlns="http://www.iicmva.com/CoverageVerification/"> 
     <Detail> 
     <PolicyInformation> 
      <CoverageStatus> 
      <ResponseDetails> 
       <ResponseCode>CONFIRMED</ResponseCode> 
       <UnconfirmedReasonCode/> 
      </ResponseDetails> 
      </CoverageStatus> 
     </PolicyInformation> 
     </Detail> 
    </CoverageResponse> 
    </soap:Body> 
</soap:Envelope> 

我一直試圖做的是不工作:

Dim doc As New XmlDocument 
doc.LoadXml(result) 

Dim root = doc.DocumentElement.FirstChild.FirstChild 
Dim responseDetails = root.SelectSingleNode("descendant::Detail/PolicyInformation/CoverageStatus/ResponseDetails") 
Dim responseCode = responseDetails.ChildNodes(0).InnerText 
Dim unconfirmedReasonCode = responseDetails.ChildNodes(1).InnerText 

Console.WriteLine("Response Details:" & vbCrLf & vbCrLf & responseCode & " " & unconfirmedReasonCode) 
Console.ReadLine() 

回答

2

這是關於選擇與默認命名空間 XML文檔的內容,其中最常見問題 - 請海用於XPath和默認命名空間。 提示:閱讀有關XmlNamespaceManager類。

一個相對簡單的和選擇的更少可讀方法:

使用:

/*/*/*/*/*/*/*/*[local-name()='ResponseCode'] 

和使用:

/*/*/*/*/*/*/*/*[local-name()='UnconfirmedReasonCode'] 

XSLT - 基於驗證

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="/"> 
    <xsl:copy-of select= 
    "/*/*/*/*/*/*/*/*[local-name()='ResponseCode']"/> 
    <xsl:copy-of select= 
    "/*/*/*/*/*/*/*/*[local-name()='UnconfirmedReasonCode']"/> 
</xsl:template> 
</xsl:stylesheet> 

當這個變換所提供的XML文檔施加:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
    <CoverageResponse xmlns="http://www.iicmva.com/CoverageVerification/"> 
     <Detail> 
     <PolicyInformation> 
      <CoverageStatus> 
      <ResponseDetails> 
       <ResponseCode>CONFIRMED</ResponseCode> 
       <UnconfirmedReasonCode/> 
      </ResponseDetails> 
      </CoverageStatus> 
     </PolicyInformation> 
     </Detail> 
    </CoverageResponse> 
    </soap:Body> 
</soap:Envelope> 

兩個正確地選擇節點是輸出:

<ResponseCode xmlns="http://www.iicmva.com/CoverageVerification/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">CONFIRMED</ResponseCode> 
<UnconfirmedReasonCode xmlns="http://www.iicmva.com/CoverageVerification/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" /> 
+0

感謝一束! –

+0

@Scott:不客氣。 –