Search code examples
javaxmlsaxparserdom4j

read elements from an xml file using SAXReader


Am trying to read the below xml content using SAXReader I have to read the child elements of node name "SelogerListController". The node name "SelogerListController" contains 3 child nodes .

My main aim is to get the 3rd node's child elemnts of node name "SelogerListControllerlike"

 src="http://res/Favorite_Badge.png" ,src="http://res/sm_aries.png"

and

 src="http://res/sm_cancer.png"  and http://res/Favorite_Badge.png
 ...............

and the remining details also..

Code using

SAXReader reader = new SAXReader();
        Document document;
        String xPath = "//XREClientView/XREClientView[5]";
        String nodeName = null;

        List<Element> childViews;
        try {
            document = reader.read("F://TestNewXMLAfter.xml");

            List<Node> nodes = document.selectNodes(xPath);
            for (Node node : nodes) {
                System.out.println("name :: " + node.valueOf("@name"));
                System.out.println(node.getPath());
                nodeName = node.valueOf("@name");
                if (nodeName.equals("SelogerListController")) {
                    childViews = ((Element) node).elements();

                    for (Element element : childViews) {
                        Element ele = element.element("XREClientImage");
                    }

                    break;
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Solution

  • The XPath you show in your post is:

    //XREClientView/XREClientView[5]
    

    This says find an XREClientView which contains at least five child nodes named XREClientView and return the fifth one. The XPath should start

    //XREClientView[@name='SelogerListController']/...
    

    where you can work out what to substitute for .... It's not entirely clear what unique attribute values you can use to find the nodes you're interested in.