Namespace handling in Groovys XmlSlurper

后端 未结 2 1188
慢半拍i
慢半拍i 2020-12-31 11:51

The situation:

def str = \"\"\"
  
    sudo 
    make me a sandwich!<         


        
2条回答
  •  生来不讨喜
    2020-12-31 12:10

    By default XMLSlurper is not namespace aware. This can be turned on by declaring namespaces with the declareNamespace Method.

    def str = """ 
    
      sudo 
      make me a sandwich!
    
    """ 
    def xml = new XmlSlurper().parseText(str).declareNamespace('weird':'http://localhost/')
    println xml.bar // without namespace awareness, will print "sudo make me a sandwich!"
    println xml.':bar' // will only print "sudo"
    println xml.'weird:bar' // will only print "make me a sandwich!"
    

    The output is:

    sudo make me a sandwich!
    sudo
    make me a sandwich!
    

    The first println will still not be namespace aware. The second println will only print the tag without namespace. If you qualify element with the prefix shown in the third println you only get the namespaced tag.

提交回复
热议问题