Malus Domestica Malus Domestica - 22 days ago 7
Java Question

Java How to get content according to the id of tag from XML file

Here is the xml file.

<columns>
<c id="3">c</c>
<b id="2">b</b>
<a id="1">a</a>
<d id="4">d</d>
<e id="5">e</e>
</columns>


I have to store the contents in an array and use a loop to show them.

The "id" should be in ascending order.

How can I get the content "a" in the tag according to the "id" in Java?



The expected output should be:

a
b
c
d
e


The updated xml file here

And I just want the content a-e.

<data>
<columns>
<c id="3">Content of c</c>
<b id="2">Content of b</b>
<a id="1">Content of a</a>
<d id="4">Content of d</d>
<e id="5">Content of e</e>
</columns>
<xyz id="1">
<hi>hi</hi>
</xyz>
<xyz id="2">
<bye>bye</bye>
</xyz>
</data>

Answer

------------------------------ORIGINAL XML------------------------------

First, the XML file has an error, the final element is "/columns":

<?xml version="1.0" encoding="UTF-8"?>
<columns>
  <c id="3">Content of c</c>
  <b id="2">Content of b</b>
  <a id="1">Content of a</a>
  <d id="4">Content of d</d>
  <e id="5">Content of e</e>
</columns>

Then, try this:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;


public class orderXML {

    public static void main(String argv[]) {

        try {

            File fXmlFile = new File("src/Content.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nList = doc.getDocumentElement().getChildNodes();

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println("    READ ORDER              ");
            System.out.println("++++++++++++++++++++++++++++");     

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    Element eElement = (Element) nNode;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());
                }
            }           

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println("    ID ORDER                ");
            System.out.println("++++++++++++++++++++++++++++");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node node=returnNodeByValue(nList, "id", String.valueOf(temp));

                if(node!=null && node.getNodeType() == Node.ELEMENT_NODE){
                    System.out.println("\nCurrent Element :" + node.getNodeName());
                    Element eElement = (Element) node;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());   
                }               
            }       
        } catch (Exception e) {
            e.printStackTrace();
        }
      }

    /**
     * Returns a Node by attribute name and attribute value.
     * @param nodeList  NodeList where we find the node
     * @param attributeName Attribute name to search
     * @param attributeValue Attribute name to search
     * @return If exists a node with attributeName and attributeValue returns this Node,
     *      if not exists, returns null
     */
    private static Node returnNodeByValue(NodeList nodeList, String attributeName, String attributeValue) {
        for (int temp = 0; temp < nodeList.getLength(); temp++) {

            Node nNode = nodeList.item(temp);           

            if (nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;
                String returnAttribute = eElement.getAttribute(attributeName);
                if(returnAttribute.equals(attributeValue)){
                    return nNode;
                }
            }                           

        }
        return null;
    }
}

Output:

Root element :columns

++++++++++++++++++++++++++++

READ ORDER  

++++++++++++++++++++++++++++

Current Element :c Id : 3 Content : Content of c

Current Element :b Id : 2 Content : Content of b

Current Element :a Id : 1 Content : Content of a

Current Element :d Id : 4 Content : Content of d

Current Element :e Id : 5 Content : Content of e

++++++++++++++++++++++++++++

ID ORDER    

++++++++++++++++++++++++++++

Current Element :a Id : 1 Content : Content of a

Current Element :b Id : 2 Content : Content of b

Current Element :c Id : 3 Content : Content of c

Current Element :d Id : 4 Content : Content of d

Current Element :e Id : 5 Content : Content of e

------------------------------MODIFIED XML------------------------------

XML file:

<data>
  <columns>
    <c id="3">Content of c</c>
    <b id="2">Content of b</b>
    <a id="1">Content of a</a>
    <d id="4">Content of d</d>
    <e id="5">Content of e</e>
  </columns>
  <xyz id="1">
    <hi>hi</hi>
  </xyz>
  <xyz id="2">
    <bye>bye</bye>
  </xyz>
</data>

Code:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.util.ArrayList;

public class orderXML {

    public static void main(String argv[]) {

        try {

            File fXmlFile = new File("src/contentUpdate.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            //  1 - Get childrens of root

            NodeList nList = doc.getDocumentElement().getChildNodes();
            NodeList childrenOfColumns = null;
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());

                    //  2 - If this element is columns, we store it...

                    if(nNode.getNodeName().equals("columns")){
                        Element eElement = (Element) nNode;
                        childrenOfColumns = eElement.getChildNodes();
                    }
                }
            } 

            //  3 - Finaly we use "childrenOfColumns"

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println(" READ ORDER INSIDE COLUMNS ");
            System.out.println("++++++++++++++++++++++++++++");     

            for (int temp = 0; temp < childrenOfColumns.getLength(); temp++) {

                Node nNode = childrenOfColumns.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    Element eElement = (Element) nNode;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());
                }
            }           

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println(" ID ORDER INSIDE COLUMNS    ");
            System.out.println("++++++++++++++++++++++++++++");

            for (int temp = 0; temp < childrenOfColumns.getLength(); temp++) {

                Node node=returnNodeByValue(childrenOfColumns, "id", String.valueOf(temp));

                if(node!=null && node.getNodeType() == Node.ELEMENT_NODE){
                    System.out.println("\nCurrent Element :" + node.getNodeName());
                    Element eElement = (Element) node;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());   
                }               
            }       
        } catch (Exception e) {
            e.printStackTrace();
        }
      }

    /**
     * Returns a Node by attribute name and attribute value.
     * @param nodeList  NodeList where we find the node
     * @param attributeName Attribute name to search
     * @param attributeValue Attribute name to search
     * @return If exists a node with attributeName and attributeValue returns this Node,
     *      if not exists, returns null
     */
    private static Node returnNodeByValue(NodeList nodeList, String attributeName, String attributeValue) {
        for (int temp = 0; temp < nodeList.getLength(); temp++) {

            Node nNode = nodeList.item(temp);           

            if (nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;
                String returnAttribute = eElement.getAttribute(attributeName);
                if(returnAttribute.equals(attributeValue)){
                    return nNode;
                }
            }                           

        }
        return null;
    }
}

Output:

Root element :data

Current Element :columns

Current Element :xyz

Current Element :xyz

++++++++++++++++++++++++++++

READ ORDER INSIDE COLUMNS

++++++++++++++++++++++++++++

Current Element :c Id : 3 Content : Content of c

Current Element :b Id : 2 Content : Content of b

Current Element :a Id : 1 Content : Content of a

Current Element :d Id : 4 Content : Content of d

Current Element :e Id : 5 Content : Content of e

++++++++++++++++++++++++++++

ID ORDER INSIDE COLUMNS

++++++++++++++++++++++++++++

Current Element :a Id : 1 Content : Content of a

Current Element :b Id : 2 Content : Content of b

Current Element :c Id : 3 Content : Content of c

Current Element :d Id : 4 Content : Content of d

Current Element :e Id : 5 Content : Content of e

Comments