相关文章推荐
灰常酷的炒面  ·  vue v-for 嵌套-掘金·  1 年前    · 
曾经爱过的八宝粥  ·  ts1184 modifiers ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

def str = """ 
<foo xmlns:weird="http://localhost/">
  <bar>sudo </bar>
  <weird:bar>make me a sandwich!</weird:bar>
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!
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.

Thank you, that explains a few things :) I'm parsing different xmls and I do not know which namespaces they are using; is there any possibility to achieve the output of println xml.':bar' apart from parsing the root element for namespaces and declaring them? – codeporn Dec 29, 2011 at 17:04 I think that XmlSlurper is namespace aware by default, since new XmlSlurper() -> new XmlSlurper(false, true): stackoverflow.com/questions/33418826/… – jalopaba Nov 3, 2015 at 9:59 Ugh. For some reason, this isn't working for me. I'm parsing an RSS document with namespaces declared in the headers. I can access rss.channel.link but rss.channel.'atom:link'.text() and rss.channel.'atom:link'.@href.text() all return blank values. :( – Umopepisdn May 15, 2016 at 20:55 I fixed it with .declareNamespace('atom':'w3.org/2005/Atom'). But argh, why should I have to do this when the header is in the xmlns element in the response? – Umopepisdn May 15, 2016 at 21:06

I know this was answered a while ago, but here's an alternative for anyone else facing the same issue. The XmlSlurper class has three constructors, a couple of which allow you to specify you want it to be namespace-aware.

public XmlSlurper(boolean validating, boolean namespaceAware)

Declare the slurper by calling new XmlSlurper(false, true). I hope this is useful to others.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.