Extract all the recurring element of XML using java

Sahilkhan :

My XML looks like below and I need to extract multiple ID element in an output xml:-

<?xml version="1.0" encoding="utf-8"?>
<Stock>
    <PIdentification>
    <CatalogVersion></CatalogVersion>
    <AccountID></AccountID>
    <CustomerId></CustomerId>
    </ProviderIdentification>
    <Product>
        <ArticleName>Monitors</ArticleName>
        <BaseUnit></BaseUnit>
        <Notes></Notes>
        <ID>11f13e2e-ae97-45b5-a9a9-23fa7f6bb767</ID>
        <ID>b22834c0-a570-4e6b-97c3-5067a14d118d</ID>
        <ID>ed458593-5e1a-4dc1-94f0-a66eeef2dd79</ID>
        <ID>d25584a9-1db2-48cf-9a70-9b81e5a7e7f2</ID>
    </Product>
</Stock>

I have used "Nodelist" to extract "ID" but I am getting just one element and not all 4, below is the part of the code:-

{   
    Node IDNode = element.getElementsByTagName("ID").item(0);
    IDXml = toStringXml(IDNode , true);
}

I am not able to reiterate for look to get all the IDs, please let me know how to get all ID, any help is appreciated.

    private static String toStringXml(Node elt, boolean xmlDeclaration) 
    throws TransformerException {
     TransformerFactory transformerFactory = TransformerFactory
        .newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    if(xmlDeclaration)
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(elt);
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(source, result);

    return result.getWriter().toString();
    }
Penguin74 :

You got all id's but you are only looking at first item with .item(id).

Method getElementsByTageName("ID") returns you NodeList so you can got trough all ids for example like that:

File xmlFile = new File("src/main/resources/example.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document element = dBuilder.parse(xmlFile);

NodeList list = element.getElementsByTagName("ID");
for (int i = 0; i < list.getLength(); i++){
    Node specificIDNode = list.item(i);
    System.out.println(specificIDNode.getTextContent());
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420224&siteId=1