How to read the coloned attribute names (Eg. model:name) while parsing xml using XmlSlurper

StackOverflow https://stackoverflow.com/questions/21929139

  •  14-10-2022
  •  | 
  •  

Question

I have an XMl where an attribute is e.g. model:name.

After upgrading to Grails 2, it fails to extract the attribute using

it.@"model:name".text()

I have read How to read the hyphenated attribute names (Eg. model_name) while parsing xml using XmlSlurper and followed the links too, but nothing points me towards documentation on how to handle coloned attributes.

Final solution for xml:lang attributes: it.attributes()['{http://www.w3.org/XML/1998/namespace}lang']

Était-ce utile?

La solution

What you refer to as a "coloned attribute" is actually an attribute that is in a namespace. The default behaviour of XmlSlurper is to ignore namespaces in the sense that when you ask it for a node name without a colon it will find nodes with that local name regardless of namespace. So you may find that simply

it.@name

finds the attribute you're interested in. If that doesn't work then you'll need to call declareNamespace on the object you got back from XmlSlurper, to map a prefix to the namespace URI that corresponds to model: in the XML document (look for the xmlns:model="http://example.com" or whatever in the XML)

def xml = new XmlSlurper().parse(...).declareNamespace(
    model:"http://example.com")

and then model:name should work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top