XML 名称空间的使用可能会使事情复杂化。如果您知道 XML sn-p 正在使用如图所示的确切名称空间前缀,您可以在 XmlSlurper 中禁用名称空间感知并使用“prefix:elementName”作为引用元素。
def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<CanOfferProductResponse xmlns="urn:iQQ:API:22:iQQMessages.xsd"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
// the second constructor argument controls namespace awareness
def env = new XmlSlurper(false, false).parseText(xml)
def namespace = env.'SOAP-ENV:Body'.CanOfferProductResponse.@xmlns
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
但是,如果默认命名空间并不总是在 CanOfferProductResponse 元素上定义,或者命名空间前缀并不总是一致,例如Envelope 元素具有xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 属性而不是xmlns:SOAP-ENV=...,那么这种方法将不起作用。
命名空间感知方法将涉及调用lookupNamespace 方法并传入一个空字符串参数(这意味着该元素的默认命名空间):
// by default, XmlSlurper instances are namespace aware
def env = new XmlSlurper().parseText(xml)
def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
但由于命名空间是继承的,这种方法意味着 lookupNamespace 方法仍然会返回 'urn:iQQ:API:22:iQQMessages.xsd',即使 @987654329 上实际上没有 xmlns 属性@元素,例如
def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:iQQ:API:22:iQQMessages.xsd">
<SOAP-ENV:Body>
<CanOfferProductResponse />
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
def env = new XmlSlurper().parseText(xml)
def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
(此示例使用 Groovy 2.5 执行)