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">
節點內的所有內容,但我仍然希望能夠解析它。
的GPathResult從parseText()
方法返回允許你調用declareNameSpace(Map m)
一個命名空間添加到文檔,像這樣:
def slurper = XmlSlurper().parseText(someXMLText).declareNamespace(soap:'http://schemas.xmlsoap.org/soap/envelope/')
但我不正確認識如何調用declareNamespace()
在GPathResult指定匿名命名空間(xmlns="KaseyaWS"
)。
注:
,如果您需要在命名空間和XML進行解析,以節點的方式更多的控制,您可以使用
XmlParser
:所以,你可以不用擔心的命名空間解析,如果你想要XmlParser不知道名稱空間,就像XmlSlurper一樣,你可以使用這個'xmlParser.setNamespaceAware(false)'。注意:在我的版本(groovy 2.3.7)中,如果我們在XmlParser構造函數中使用它,會有一個忽略這個假參數的錯誤。所以,我們必須明確地調用setter – Topera