views:

29

answers:

1

I have following xml file:

<doc_xml>
<nodes>
  <node id='1' spec="{spec_a=0.9, spec_b=0.1}" />
  <node id='2' spec="{spec_a=0.1, spec_b=0.3}" />
  <node id='3' spec="{}" />
</nodes>
</doc_xml>

This code was created using Groovy MarkupBuilder.

Now I would like to parse this file in a groovy script:

def xml = new XmlParser().parseText(getDocXmlAsString());

xml.nodes.node.each {
   Map spec = it.@spec; // here I got an exception org.codehaus.groovy.runtime.typehandling.GroovyCastException

}

but I keep getting this exception:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{spec_a=0.9, spec_b=0.1}' with class 'java.lang.String' to class 'java.util.Map'

My question, how to parse an xml attribute which is a map?

A: 
tim_yates
How to confugure Groovy MarkupBuilder to produce "[:]" instead of "{:}"?
Skarab
I agree that storing Map in a attribute is not the best practice. But I am creating a prototype so I do not want to spend tou much effort in writing a parser for a complex xml hierarchy.
Skarab
I see what you mean about MarkupBuilder producing that map format... I have added a possible solution to the bottom of my answer... Hope it helps :-)
tim_yates
Thanks for your help. I really appreciate that you provide so comprehensive answer for my question.
Skarab
No worries, good luck with it, and glad I could help :-)
tim_yates