javaibm-integration-busextended-sqlibm-app-connect

How to traverse an XML tree in java compute node


I am facing a situation while using IIB v10 where a SOAP web service is sending XML response that contains both English and REVERSED Arabic in the same XML element.

Example:

<note>
  <to>Tove   رمع</to>
  <from>Jani  ريمس</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

It should looks like this

<note>
  <to>Tove   عمر</to>
  <from>Jani  سمير</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

So I already prepared some Java code that takes a string , split it as words in a string array and check if a word is an arabic word then it will reverse it then re-concatenate the string.

The issue is that the backend response is a bit large and I need to loop over each element in the XML tree so is there any way in the Java compute Node that allows traversing each and every element in the tree and get its value as a string ?


Solution

  • Recursion is your friend. Invoke following function with the root element:

    import com.ibm.broker.plugin.MbElement;
    import com.ibm.broker.plugin.MbException;
    import com.ibm.broker.plugin.MbXMLNSC;
    
    public void doYourThing(MbElement node) throws MbException {
        MbElement child = node.getFirstChild();
        while (child != null) {
            int specificType = child.getSpecificType();
            if (specificType == MbXMLNSC.FIELD) {
                String value = child.getValueAsString();
                // Do your thing
            }
            doYourThing(child);
            child = child.getNextSibling();
        }
    }