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...
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.
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.
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.
groovy.xml.Namespace. public class Namespace extends Object. A simple helper class which acts as a factory of QName instances.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With