I am trying to read an attribute while parsing XML using XmlSlurper in Groovy. When I try to read the hyphenated attribute model-number
I am getting an exception.
<router name="b" id="x" manufacturer-id="e" model-number="a"/>
You can also handle hyphenated (and non-hyphenated) attributes by using variables, which is helpful at times just in generic processing of XML with unknown or inconsistent attributes (such as, perhaps, submitted web forms).
Here you can see an example that loops through all of the attributes in the XML, regardless of whether they have a hypen or not:
def xml = "<router name='b' id='x' manufacturer-id='e' model-number='a'/>"
def router = new XmlSlurper().parseText(xml)
for (String attrib : router.attributes().keySet()) {
value = router.@"$attrib".text()
println("${attrib}=${value}")
}
def a = "<router name='b' id='x' manufacturer-id='e' model-number='a'/>"
def router = new XmlSlurper().parseText(a)
println router.@'manufacturer-id'
println router.@'name'
println router.@'id'
println router.@'model-number'
i tried this on console and it is working.
From the Groovy documentation on XMLSlurper:
If your elements contain characters such as dashes, you can enclose the element name in double quotes.
Example:
def myXML = '<router name="b" id="x" manufacturer-id="e" model-number="a"/>'
def router = new XmlSlurper().parseText(myXML)
def attr = router.@"model-number".text()
Tested and worked for me.
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