Tutorial XML Parser Groovy Namespace Handling

11,351

Solution 1

Your expression was incorrect - the xml var is already the root element of the xml document (in this case soap:Envelope) - so you just need to traverse from there. So, the expression you're looking for is:

println xml[soapns.Body][ordns.MG_Input].Accnr[0].text()

Solution 2

Tip for others:

you can just print the String that you parsed. for example, above print xml after this line xml = new XmlParser().parseText(input.getText()) , then you will get the top element, it will look similar to a JSON array, then you can easily traverse on that. Don't include the topmost element you see.

Share:
11,351
Booyeoo
Author by

Booyeoo

Updated on June 05, 2022

Comments

  • Booyeoo
    Booyeoo almost 2 years

    i found this supergroovy function of XmlParser().parseText(...).

    It works fine for me without namespaces... now i have the following XML (SoapRequest):

    <?xml version="1.0" encoding="UTF-8"?>
       <soap:Envelope xmlns:soap="http://xxx" xmlns:xsd="http://xxy" 
         xmlns:xsi="http://xxz">
           <soap:Body>
             <MG_Input xmlns="http://yxx">
                <Accnr>001</Accnr> 
                [...]
    

    My target is to acquire the Accnr over the XmlParser. I assumed that it could work this way:

    input = new File('c:/temp/03102890.xml-out')
    
    def soapns = new groovy.xml.Namespace("http://xxx",'soap')
    def xsdns = new groovy.xml.Namespace("http://xxy")
    def xsins = new groovy.xml.Namespace("http://xxz")
    def ordns = new groovy.xml.Namespace("http://yxx")
    
    
    
    xml = new XmlParser().parseText(input.getText())
    println xml[soapns.Envelope][soapns.Body][ordns.MG_Input][Accnr][0].text()
    

    But this doesnt really work...

    Has anybody an idea of how to handle this 'easy'? I just cant get it to work with examples from google...

  • Booyeoo
    Booyeoo almost 13 years
    Hmm i dont know why, but it works now with println xml[soapns.Body].MG_Input.Accnr[0].text() I think there is another good way to solve it with GPath. But this is also a further task to learn.