Hi!

I would like to read XML file from my SWING application, however list.size() returns 0. Why does it happen? Thanks!

private void open() {
        SAXBuilder builder = new SAXBuilder();
    	File xmlFile = new File(openedFileName());

        try{
    	   Document document = (Document) builder.build(xmlFile);
           Element rootNode = document.getRootElement();
           List list = rootNode.getChildren("Panel");

           for (int i=0; i< list.size(); i++)
           {
             Element node = (Element) list.get(i);

             System.out.println("Name : "  + node.getChildText("name"));
       	     System.out.println("X : "  + node.getChildText("x"));
      	     System.out.println("Y : "  + node.getChildText("y"));
      	     System.out.println("Width : "  + node.getChildText("width"));
             System.out.println("Height : "  + node.getChildText("height"));
           }

    	 }catch(IOException io){
    		System.out.println(io.getMessage());
    	 }catch(JDOMException jdomex){
    		System.out.println(jdomex.getMessage());
    	}
    }

Recommended Answers

Ok, in the XML fragment you posted above, <Panel> is actually your root element rather than a child. If you add another element level above <Panel> called <Locations> or <Project> or whatever, your getChildren() code should work fine.

Jump to Post

Pls note that Document is org.w3c.dom.Document

Second if you know the structure of the XML file then you can implement like below

NodeList nL = doc.getTagByName("TagName");

for(int i=0;i<nL.getLength();i++){
Node nod = nL.item(i);
//Process accordingly
}

Note: if any typing mistake please correct

Jump to Post

It's backwards. Your root element is the very first top-level element in a document. In the above, <Panel> is the root. You need the Panel elements to be children of the root, so there needs to be one more level above Panel. I just threw out Project or Locations as …

Jump to Post

Do you have multiple Panel elements defined under the root?

Jump to Post

All 15 Replies

try list.length()

> try list.length()
Why would she want to try a method that doesn't exist? That doesn't seem very useful to me.

Without seeing the XML file structure it's impossible to say. Are you certain that there are <Panel> elements as direct children of the root?

I am not sure about SAXBuilder but the below code will work

DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
DocumentBuilder dB = dBF.newDocumentBuilder();
Document doc = dB.parse(new File(xml File Name));

//Now use Node/NodeList and read the data

Hi!

Thanks for recommendations.

XML file:

<?xml version="1.0" encoding="UTF-8" ?> 
- <Panel>
  <name>label</name> 
  <x>432</x> 
  <y>271</y> 
  <width>80</width> 
  <height>75</height> 
  <name>label</name> 
  <x>474</x> 
  <y>84</y> 
  <width>86</width> 
  <height>81</height> 
  </Panel>

I also tried DocumentBuilderFactory as it was proposed, but I got the error message (see below).

private void open() throws SAXException, ParserConfigurationException {
        //SAXBuilder builder = new SAXBuilder();
    	//File xmlFile = new File(openedFileName());

        try{
           DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
           DocumentBuilder dB = null;

           dB = dBF.newDocumentBuilder();
           Document doc = (Document) dB.parse(new File(openedFileName()));
    	   //Document document = (Document) builder.build(xmlFile);
           Element rootNode = doc.getRootElement();
           List list = rootNode.getChildren("Panel");

           for (int i=0; i< list.size(); i++)
           {
             Element node = (Element) list.get(i);

             System.out.println("Name : "  + node.getChildText("name"));
       	     System.out.println("X : "  + node.getChildText("x"));
      	     System.out.println("Y : "  + node.getChildText("y"));
      	     System.out.println("Width : "  + node.getChildText("width"));
             System.out.println("Height : "  + node.getChildText("height"));
           }

    	 }catch(IOException io){
    		System.out.println(io.getMessage());
    	 }
    }
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl cannot be cast to org.jdom.Document
        at mainClassesPack.Menu.open(Menu.java:194)
        at mainClassesPack.Menu.actionPerformed(Menu.java:82)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
        at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1223)
        at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1264)
        at java.awt.Component.processMouseEvent(Component.java:6263)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6028)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2478)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Without seeing the XML file structure it's impossible to say. Are you certain that there are <Panel> elements as direct children of the root?

Ok, in the XML fragment you posted above, <Panel> is actually your root element rather than a child. If you add another element level above <Panel> called <Locations> or <Project> or whatever, your getChildren() code should work fine.

Pls note that Document is org.w3c.dom.Document

Second if you know the structure of the XML file then you can implement like below

NodeList nL = doc.getTagByName("TagName");

for(int i=0;i<nL.getLength();i++){
Node nod = nL.item(i);
//Process accordingly
}

Note: if any typing mistake please correct

The original DOM builder code was fine. It was just a slight issue with the document structure.

I've changed XML as follows:

<?xml version="1.0" encoding="UTF-8" ?> 
- <Panel>
- <Location>
  <name>label</name> 
  <x>432</x> 
  <y>271</y> 
  <width>80</width> 
  <height>75</height> 
  <name>label</name> 
  <x>474</x> 
  <y>84</y> 
  <width>86</width> 
  <height>81</height> 
  </Location>
  </Panel>

...and I've used my original code piece. But System.out.println(list.size()); provides 0 again:( What is wrong?

The original DOM builder code was fine. It was just a slight issue with the document structure.

It's backwards. Your root element is the very first top-level element in a document. In the above, <Panel> is the root. You need the Panel elements to be children of the root, so there needs to be one more level above Panel. I just threw out Project or Locations as possibilities. You can call it whatever you want.

<someRoot>
  <Panel>
    ..
  </Panel>
</someRoot>

Ok, thank you. Now it works, but there is one more question: why only first record is
accessed?
1
Name : label
X : 432
Y : 271
Width : 80
Height : 75

I tried also for (int i=0; i<=list.size(); i++) , but it failed.

Do you have multiple Panel elements defined under the root?

Hmm..ok, I understand the problem. BTW, this XML file was generated by another piece of JAVA code, which must be updated now to produce something like:

<Location>
<Panel>
...
</Panel>
<Panel>
...
</Panel>
</Location>

Thank you!

Suppose your xml is like below

<?xml version="1.0" encoding="UTF-8" ?> 
<Panel>
<name>
<x>432</x> 
<y>271</y> 
<width>80</width> 
<height>75</height> 
</name> 
<name>
<x>474</x> 
<y>84</y> 
<width>86</width> 
<height>81</height> 
</name>
</Panel>

use the below code

NodeList nL = doc.getElementsByTagName("Panel");
            for (int i = 0; i < nL.getLength(); i++) {
                Node nod = nL.item(i);
                if (nod.getNodeType() == Node.ELEMENT_NODE) {
                    Element el = (Element) nod;
                    NodeList nL1 = el.getElementsByTagName("name");
                    for (int j = 0; j < nL1.getLength(); j++) {
                        Node nod1 = nL1.item(j);
                        if (nod.getNodeType() == Node.ELEMENT_NODE) {
                            Element el2 = (Element) nod1;
                            Node nod2 = el2.getElementsByTagName("x").item(0);
                            System.out.println("x == " + nod2.getTextContent());
                            nod2 = el2.getElementsByTagName("y").item(0);
                            System.out.println("y == " + nod2.getTextContent());
                            nod2 = el2.getElementsByTagName("width").item(0);
                            System.out.println("width == " + nod2.getTextContent());
                            nod2 = el2.getElementsByTagName("height").item(0);
                            System.out.println("height == " + nod2.getTextContent());
                        }
                    }
                }
            }

Ok, thank you as well! The problem is solved now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.