Search code examples
javaxmlxml-parsingnashorn

Retrieve duplicated element using Jetty XML Parser


I'm currently using Jetty XML Parser in JavaScript Nashorn to retrieve certain nodes in an XML payload and I want to retrieve a certain child node with the same name. For example:

<MessageV1 xmlns="http://schemas.somecompany.com.au/somemessage.xsd">
    <DeliverWeb>
       <DeliveryMethod>WebService1</DeliveryMethod>
       <DeliverToUrl>https://someurl.com/class/Webservices</DeliverToUrl>
       <DeliverToSomewhere>false</DeliverToSomewhere>
    </DeliverWeb>
    <DeliverWeb>
       <DeliveryMethod>WebService2</DeliveryMethod>
       <DeliverToUrl>https://login.salesforce.com/services/someid</DeliverToUrl>
       <DeliverToSomewhere>false</DeliverToSomewhere>
    </DeliverWeb>
 </MessageV1>

My code:

    //Convert XML input string to input stream
    var parser = new UsersXmlParser()
    var input = new ByteArrayInputStream(xmlStringBuilder.toString().getBytes("UTF-8"));

    //parse XML
    var inputMessage = parser.parse(input)

   //extract DeliverWeb using tag string
    var webservice1 = inputMessage.get("DeliverWeb")

   //extract DeliverWeb using i node (This will count the number of tag)
    var webservice1 = inputMessage.get(1)
    var webservice2 = inputMessage.get(3)

As you can see in the code, if I use tag string I won't be able to get the second DeliverWeb as it only return the first child node:

    <DeliverWeb>
       <DeliveryMethod>WebService1</DeliveryMethod>
       <DeliverToUrl>https://someurl.com/class/Webservices</DeliverToUrl>
       <DeliverToSomewhere>false</DeliverToSomewhere>
    </DeliverWeb>

Is there a way I can retrieve the second deliverweb using the name tag following up with the number of the child node for example:

    var webservice1 = inputMessage.get("DeliverWeb")[1]

However, that won't work as it will return:

<DeliveryMethod>WebService1</DeliveryMethod>

If it helps, here's the jetty XML library link: https://archive.eclipse.org/jetty/7.0.0.M3/apidocs/org/eclipse/jetty/xml/XmlParser.Node.html

Any ideas would be much appreciated!


Solution

  • Well, the docs for <XmlParser.Node>.get describe it as "Get the first child node with the tag."

    If you want to get all the tags, there's <XmlParser.Node>.iterator which returns an Iterator containing all the matching child nodes with the tag.

    var webservices = inputMessage.iterator("DeliverWeb");
    
    var webservice1 = webservices.next();
    var webservice2 = webservices.next();