Dave Cruise
Dave Cruise

Reputation: 443

get value from xml node by search in java

I have need to know whether my logic is correct or not because I am new to play with XML node. Here is my code. JAVA

        try{
        File inputFile = new File("C:\\Users\\luenwong\\Desktop\\decoded.txt");
        Scanner scanner = new Scanner( new File("C:\\Users\\luenwong\\Desktop\\decoded.txt"));
        String text = scanner.useDelimiter("\\A").next();
        scanner.close();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document docum = dBuilder.parse(inputFile);
        docum.getDocumentElement().normalize();
        NodeList nList = docum.getElementsByTagName("row");
        System.out.println("------------------------------");
        for(int temp=0; temp<nList.getLength();temp++){
            Node nNode = nList.item(temp);
            System.out.println("\n Current Element :" + nNode.getNodeName());
            if(nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;
                String here = eElement.getElementsByTagName("col").item(1).getTextContent();
                    if(here.indexOf("AB02") == 0)
                    {
//                    InputStream is = new ByteArrayInputStream(text.getBytes());
//                    Document doc = PositionalXMLReader.readXML(is);
//                    Node test = doc.getElementsByTagName("col").item(0);
//                    System.out.println("Student roll no : " + eElement.getElementsByTagName("col").item(0).getTextContent());
//                    System.out.println("Line number: " + test.getUserData("lineNumber"));
                    }
                }
            }
    }catch (Exception e){
        e.printStackTrace();
    }

my XML file

<?xml version="1.0" encoding="UTF-8"?>
<mapping-table>
<col-def name="Location Description" type="nocase"/>
<col-def name="Centre Code" type="nocase"/>
<col-def name="Location Code" type="nocase"/>
<col-def name="Status" type="nocase"/>
<row>
    <col>TAMAN TUN DR ISMAIL</col>
    <col>AB02</col>
    <col>CSTDI</col>
    <col>active</col>
</row>
<row>
    <col>KUALA LUMPUR CITY CENTRE (KLCC)</col>
    <col>AA02</col>
    <col>I-CTRKLCC</col>
    <col>active</col>
</row>
</mapping-table>

What I am trying to do is I wish to type "AA02" and I am able to get the result as "KUALA LUMPUR CITY CENTRE (KLCC)". My logic is that, I will be looking for the line number, and then I use the line number to -1 in order to get the result. But I do not know that is it able to find xml node by using the line number.

Upvotes: 1

Views: 1066

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

You should use an XPath instead, your code will be then much simpler to read and to maintain

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document docum = dBuilder.parse(inputFile);

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
String codeToFind = "AA02";
XPathExpression expr = xpath.compile(
    String.format("/mapping-table/row[col='%s']/col[1]", codeToFind)
);
Node node = (Node) expr.evaluate(docum, XPathConstants.NODE);
System.out.println(node.getTextContent());

Output:

KUALA LUMPUR CITY CENTRE (KLCC)

The XPath used here is /mapping-table/row[col='my code here']/col[1] meaning that we are looking for the first child col of the element row which has a child col whose text content is the code to find.

NB: The code above assumes that we have only one match, if you expect more than one match, then instead of getting a Node you need to get a NodeList using the next code:

NodeList nl = (NodeList) expr.evaluate(docum, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    System.out.println(node.getTextContent());
}

Upvotes: 2

Related Questions