How to read the hyphenated attribute names (Eg. model_name) while parsing xml using XmlSlurper
Asked Answered
L

3

10

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"/>
Lovellalovelock answered 12/10, 2011 at 7:31 Comment(0)
A
12
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.

Andersen answered 12/10, 2011 at 8:44 Comment(0)
M
3

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.

Mullen answered 12/10, 2011 at 8:41 Comment(0)
A
2

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}")
}
Adonai answered 24/2, 2014 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.