Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tutorial XML Parser Groovy Namespace Handling

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...

like image 446
Booyeoo Avatar asked Aug 19 '11 09:08

Booyeoo


People also ask

How do I parse XML in Groovy?

XML ParsingThe Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing.

Why do we use XML Surpler in groovy?

XmlSlurper evaluates the structure lazily. So if you update the xml you'll have to evaluate the whole tree again. XmlSlurper returns GPathResult instances when parsing XML. XmlParser returns Node objects when parsing XML.

What is namespace aware XML parser?

A namespace-aware parser does add a couple of checks to the normal well-formedness checks that a parser performs. Specifically, it checks to see that all prefixes are mapped to URIs.

What is groovy namespace?

groovy.xml.Namespace. public class Namespace extends Object. A simple helper class which acts as a factory of QName instances.


2 Answers

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()
like image 103
winstaan74 Avatar answered Oct 18 '22 17:10

winstaan74


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.

like image 25
Vins Avatar answered Oct 18 '22 17:10

Vins