2013-10-04 24 views
1

我正在寫一個Groovy腳本解析從Web服務的SOAP響應,以及XML指定的文件中間的命名空間:當根元素中未指定名稱空間時,解析Groovy中的名稱空間?

<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> 
     <AuthenticateResponse xmlns="KaseyaWS"> 
     <AuthenticateResult> 
      <SessionID>xxxxxxxxxx</SessionID> 
      <Method>Authenticate</Method> 
      <TransactionID>4228</TransactionID> 
      <ErrorMessage/> 
      <ErrorLocation/> 
     </AuthenticateResult> 
     </AuthenticateResponse> 
    </soap:Body> 
</soap:Envelope> 

的命名空間不只是指定一個名稱,它適用於<AuthenticateResponse xmlns="KaseyaWS">節點內的所有內容,但我仍然希望能夠解析它。

GPathResultparseText()方法返回允許你調用declareNameSpace(Map m)一個命名空間添加到文檔,像這樣:

def slurper = XmlSlurper().parseText(someXMLText).declareNamespace(soap:'http://schemas.xmlsoap.org/soap/envelope/') 

但我不正確認識如何調用declareNamespace()GPathResult指定匿名命名空間(xmlns="KaseyaWS")。

回答

3

XmlSlurper可能不知道命名空間。

def soapNs = new groovy.xml.Namespace(
        "http://schemas.xmlsoap.org/soap/envelope/", 'soap') 
def ns = new groovy.xml.Namespace("KaseyaWS", "test") //Dummy NS Prefix 
def parser = new XmlParser().parseText(someXMLText) 

assert parser[soapNs.Body][ns.AuthenticateResponse] 
        .AuthenticateResult.SessionID.text() == 'xxxxxxxxxx' 
assert parser[soapNs.Body][ns.AuthenticateResponse] 
        .AuthenticateResult.Method.text() == 'Authenticate' 
+1

注:

def slurper = new XmlSlurper().parseText(someXMLText) def result = slurper.Body.AuthenticateResponse.AuthenticateResult assert result.SessionID == 'xxxxxxxxxx' assert result.Method == 'Authenticate' assert result.TransactionID == '4228' 

,如果您需要在命名空間和XML進行解析,以節點的方式更多的控制,您可以使用XmlParser:所以,你可以不用擔心的命名空間解析,如果你想要XmlParser不知道名稱空間,就像XmlSlurper一樣,你可以使用這個'xmlParser.setNamespaceAware(false)'。注意:在我的版本(groovy 2.3.7)中,如果我們在XmlParser構造函數中使用它,會有一個忽略這個假參數的錯誤。所以,我們必須明確地調用setter – Topera

相關問題