Search code examples
javaxmlattributesdom4jchild-nodes

How can I get childnode's attribute from xml in java dom4j?


I'm trying to get the childnode's attribute from my xml file.For example,the file's name is bb.xml, The xml is just like this:

<?xml version="1.0" encoding="utf-8"?>
<aaa>
 <bbb name="MainMenu">
  <ccc name="abc" Classes="1"
           A="2"
           B="3"/>
 </bbb>
 <bbb name="Mainwindow">
  <ccc name="abc" Classes="4"
           A="3"
           B="2"/>
 </bbb>
</aaa>

and main java file is this:

    public static void main(String[] args) throws Exception {   

    Document doc = new SAXReader().read(new File("D:/bb.xml"));
    List itemList = doc.selectNodes("/aaa");
    for (Iterator iter=itemList.iterator(); iter.hasNext();) {
    Element el = (Element)iter.next();

    String name = el.attributeValue("name");
    System.out.println("name:"+name);
    String b = el.attributeValue("B");
    System.out.println("b:"+b); 
    }

I get the result in my console:

name:null
b:null

But I want the result is:

name:MainMenu
b:3
name:Mainwindow
b:2

How can figure it out?


Solution

  • Quick and dirty:

    public static void main(String[] args) throws Exception {    
        Document doc = new SAXReader().read(new File("D:/bb.xml"));
        Element root = doc.getRootElement();
        Iterator bbbIt = root.elementIterator();
        while (bbbIt.hasNext()) {
            Element bbb = ((Element) bbbIt.next());
            System.out.println("name:" + bbb.attributeValue("name"));
            Iterator cccIt = bbb.elementIterator();
            while (cccIt.hasNext()) {
                System.out.println("b:"
                        + ((Element) cccIt.next()).attributeValue("B"));
            }
        }
    
    }
    

    A better solution (because of flexibility) is to use Java native org.w3c.dom package. That way the solution would look like this:

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            org.w3c.dom.Document myDoc = db.parse(new File("D:/bb.xml"));
            org.w3c.dom.NodeList bbbNodes = myDoc.getElementsByTagName("bbb");
            for (int i=0; i < bbbNodes.getLength(); i++) {
                if (bbbNodes.item(i).hasAttributes())
                    System.out.println(bbbNodes.item(i).getAttributes().getNamedItem("name"));
                org.w3c.dom.NodeList cccNodes = bbbNodes.item(i).getChildNodes();
                for (int j=0; j < cccNodes.getLength(); j++) {
                    if (cccNodes.item(j).hasAttributes())
                        System.out.println(cccNodes.item(j).getAttributes().getNamedItem("B"));
                }
            }
    

    In any case: don't forget the closing </aaa> in your xml.