1

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.

1 Answer 1

2

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());
}
Sign up to request clarification or add additional context in comments.

12 Comments

it really works. may I have more information about xPath? because I do not really understand about this line of code. String.format("/mapping-table/row[col='%s']/col[1]", code). Maybe could you explain to me? thank you. I will mark your answer as the best answer.
I explained at the end of the answer (before the NB), it is not clear enough?
so mean that. I have to get into the exact row and always get the first column?
yes, at least it is how I understood your need, it is not what you expected?
yes. this is what i need. You are my god to me. may I ask you one more question? what does this mean? row[col='%s']? sorry for asking so much because I am trying to understand instead of copy and paste so I am able to do some modification if needed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.