Parsing an XML Document with Namespaces
在处理命名空间时,XmlParser 与 XmlSlurper 的区别比较明显:XmlParser 严格遵守命名空间;而 XmlSlurper 则默认忽略命名空间,除非你进行了声明:
def p_xml = """
<p:person
xmlns:p="
http://somewhere.org/person
"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
"
xsi:schemaLocation="
http://somewhere.org/person
http://somewhere.org/person.xsd
"
id="99" >
<p:firstname>John</p:firstname>
<p:last-name>Smith</p:last-name>
</p:person>
"""
def person = new XmlParser().parseText(p_xml)
//the firstname element cannot be found without its namespace
println person.firstname.text()
===> []
def p = new groovy.xml.Namespace("
http://somewhere.org/person
" )
println person[p.firstname].text()
===> John
println person[p.'last-name' ].text()
===> Smith
When p