roamsmart
roamsmart

Reputation: 145

xpath to get position of childnode against the parent in XML

I need to loop through all chilnodes in the parent node (callEvents) and save each time the position of the child node.(First call event, second call event...). I'm stack in how to get the position of each child node in the parent node java/xpath?

say I have the following xml:

<callEvents>
          <gprsCall>...</gprsCall>
          <gprsCall>...</gprsCall>
          <mobileOrigintaedCall>...</mobileOrigintaedCall>
          <gprsCall>...</gprsCall>
          <gprsCall>...</gprsCall>
</callEvents> 

So the code should return:

Upvotes: 0

Views: 93

Answers (2)

choroba
choroba

Reputation: 241758

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathConstants;
import java.io.StringReader;
import org.xml.sax.InputSource;

class myxml {
    static final String xml = "<callEvents>\n"
        + "<gprsCall>...</gprsCall>\n"
        + "<gprsCall>...</gprsCall>\n"
        + "<mobileOrigintaedCall>...</mobileOrigintaedCall>\n"
        + "<gprsCall>...</gprsCall>\n"
        + "<gprsCall>...</gprsCall>\n"
        + "</callEvents>";

    public static void main (String... args) throws Throwable {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xml)));

            XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("/callEvents/*");
            NodeList nodelist = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodelist.getLength(); i++) {
                System.out.println("Position: " + (i + 1)
                                   + ", name: " + nodelist.item(i).getNodeName());
            }
        } catch (Throwable e) {
            throw e;
        }
    }
}

Upvotes: 0

zx485
zx485

Reputation: 29022

Iterate over the XPath callEvents/* and use the position() function to get the position.

This is an XSLT example:

<xsl:template match="/callEvents/*">
    <xsl:value-of select="concat(local-name(),' - ',position() div 2)" />
</xsl:template>

Upvotes: 0

Related Questions