Groovy XML tip – Handling node names with periods

I came across a situation the other day where I had to write a web service where the client was going to be a popular front-end system that could dictate the structure of the request and response XML.

The request they were going to send to us was to look like this:

<DATA>
   <SERIAL.NUMBER>123456789-abcdef</SERIAL.NUMBER>
</DATA>

While one option would have been to transform (through XSLT) the request into something I preferred, that would have been unnecessary overhead as that front-end system will be the only client for the long-term foreseeable future and the request was already quite simple.  So I decided to just go ahead and process the request.

def myWebServiceMethod = {
    def xml = request.XML
    def serialNumber = xml.SERIAL.NUMBER.text()  //***LINE 3
    println "serialNumber: ${serialNumber}"
    ...  //omitted for clarity
}

Not surprisingly, this generated the output:

serialNumber:

My variable “serialNumber” was not set.  This went on to cause problems with the rest of my code.  I was certain that the problem was with the line where I set the variable (LINE 3 above).  That line was looking for a node “SERIAL” with a child node “NUMBER” and not a single “SERIAL.NUMBER” node.  The fix was simply to put quotes around node name like this:

def serialNumber = xml."SERIAL.NUMBER".text()

And now the output is:

serialNumber:  123456789-abcdef

…and now the rest of code worked as expected.

Advertisements

About stevewall123

I am a Lead Software Engineer in Minneapolis working for Thomson Reuters. I am currently working on projects using Java, JavaScript, Spring, Drools, Hazelcast, Liquibase and Tomcat. Previously, I used C#, GWT, Grails, Groovy, JMS and JBoss Drools Guvnor. In the past I have worked on projects using J2EE, Swing, Webwork, Hibernate, Spring, Spring-WS, JMS, JUnit and Ant.
This entry was posted in Grails, Groovy and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s