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

冷暖自知 提交于 2019-12-08 18:46:54

问题


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"/>

回答1:


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.




回答2:


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.




回答3:


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}")
}


来源:https://stackoverflow.com/questions/7736636/how-to-read-the-hyphenated-attribute-names-eg-model-name-while-parsing-xml-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!