Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"/>
like image 668
Nagaraj S Konaguthi Avatar asked Oct 12 '11 07:10

Nagaraj S Konaguthi


3 Answers

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}")
}
like image 172
Michael Oryl Avatar answered Oct 25 '22 07:10

Michael Oryl


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.

like image 45
erimerturk Avatar answered Oct 25 '22 05:10

erimerturk


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.

like image 33
OverZealous Avatar answered Oct 25 '22 07:10

OverZealous