0

I have an XML of the following format:

<Root> 
    <Delivery deliveryID="01">
        <Product productID="001">
           <name>test</name>
        </Product>
        ..........
        ..........
        ..........
        <Product productID="08">
           <name>test</name>
        </Product>
    </Delivery>
    <Delivery deliveryID="02">
        <Product productID="001">
           <name>test</name>
        </Product>
        ..........
        ..........
        ..........
        <Product productID="012">
           <name>test</name>
        </Product>

    </Delivery>
  </Root>

Is there any way to read only the child nodes of the first delivery element? Note that the number of child nodes inside the delivery elements could vary.

I was using the below code but it only works when I know the right number of elements that will appear inside the delivery tag. When the number of products inside first delivery changes, I have no way to find it

    NodeList nList1 = doc.getElementsByTagName("Delivery");
        for (int i = 0; i < nList1.getLength(); i++) {
           Node nNode = nList1.item(i);
           if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("Product : "+ eElement.getElementsByTagName("name").item(i).getTextContent());
    }
}

My main issue is having unknown number of child node with same name as child nodes of other nodes.

SuperCoder
  • 262
  • 1
  • 3
  • 13
  • Can't you use the 'deliveryID' to distinguish them? And why not just get the first element of your 'nList1'? – Lew Bloch Jun 08 '16 at 21:12
  • There is no `MerchandiseID` element in your XML. Is the position between `Product` elements? – Beck Yang Jun 08 '16 at 22:37
  • Do you need to return the first `` under each distinct ``? Simply run [XPath](https://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.html): `//Delivery/Product[1]` and then iterate off returned node list. – Parfait Jun 09 '16 at 00:49
  • I need to generate separate XML's for each delivery. That means first XML would have all products listed under delivery 01. The second XML would have all products listed under delivery 02. The number of products in each delivery could vary. That's where I'm having trouble. If there were fixed number of products, I could've went by products[0] t products[7]. But unfortunately, the number of products is unknown. – SuperCoder Jun 09 '16 at 13:08

0 Answers0