Wednesday, November 19, 2003

Using JudoScript to Convert XML into Java HashMap.

I'm finally a convert to the ranks of JudoScripters. The following example doesn't show the Java code (about 15 lines of code) that invokes the JudoScript because I wanted to keep this entry small.

My task was to maintain some information external to my Java program so I chose an XML format:

  <requiredNodes>
    <message type="all">
      <requiredNode name="messageHeader" xpath="/eanucc:envelope/messageHeader"/>
    </message>
    <message type="eanucc:tradeItemDocument">
      <requiredNode name="tid.gtin" xpath="/eanucc:envelope/../gtin"/>
      <requiredNode name="tid.glnOfInformationProvider" xpath="/eanucc:envelope/../gln"/>
    </message>
  </requiredNodes>

In order to convert this file into an easily used Java object, I used JudoScript:

	// ReadRequiredNodes.judo

	requiredNodes = javanew java.util.HashMap();
	$$bsf.registerBean("requiredNodes", requiredNodes);

	do BRRequiredNodesFileName as xml {
		<message>:
			messageMap = requiredNodes.get($_.getAttrValue(0));
			if messageMap == null {
				messageMap = javanew java.util.HashMap();
				requiredNodes.put($_.getAttrValue(0), messageMap);
			}
		<requiredNode>:
			messageMap.put($_.getAttrValue(1), $_.getAttrValue(0));
	}

Some issues to note:

  • When using SAX-based XML processing, I needed to use attributes to hold the name and xpath because the XML processing in JudoScript seems to have a flaw. The $_ variable (the current xml node) can't be used as the key in a HashMap.
  • When using SAX-based XML processing, There is no way to access attributes by name. Therefore the script uses index numbers which is brittle coding.

Overall, I found that JudoScript was easy to use and quite a compact way to handle the XML->HashMap transformation.