Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2006

Tip: Looking for answers? Try searching our database.

Parsing XML attributes with DOM

Thread view: 
Ian Wilson - 06 Nov 2006 17:06 GMT
I am trying to extract attributes of elements and failing.
In the example below I want to extract the value("Kg") of the "units"
attribute of the element weight.

My code is based on "XML Cookbook" by Ian F Darwin, OReilly.
21.4 Parsing XML with DOM.

-------------------- animals.xml ------------------------
<inventory>
  <animal type="mammal">
    <name>Fred</name>
    <species>Hippo</species>
    <weight units="Kg">1552</weight>
  </animal>
  <animal type="reptile">
    <name>Gert</name>
    <species>Croc</species>
  </animal>
</inventory>
-------------------- ParseXML.java -----------------------
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseXML {

    public static void main(String[] args) {

        String filename = "XML/animals.xml";

        String uri = "file:" + new File(filename).getAbsolutePath();
        Document doc = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(uri);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        doRecursive(doc, "");
    } // main

    private static void doRecursive(Node node, String name) {
        if (node == null)
            return;
        NodeList nodes = node.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n == null)
                continue;
            doNode(n, name);
        }
    }

    private static void doNode(Node node, String name) {
        String nodeName = "unknown";
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            if (name.length() == 0) {
                nodeName = node.getNodeName();
            } else {
                nodeName = name + "." + node.getNodeName();
            }
            doRecursive(node, nodeName);
            break;
        case Node.TEXT_NODE:
            String text = node.getNodeValue();
            if (text.length() == 0 || text.matches("\n *")
                    || text.equals("\\r")) {
                break;
            }

            // I seem to be on the wrong track here!
            String type = "";
            NamedNodeMap attrs = node.getAttributes();
            if (attrs != null) {
                Node attr = attrs.getNamedItem("type");
                if (attr != null) {
                    type = attr.getNodeValue();
                }
            }

            System.out.println(name + "(" + type + ") = '"
                                    + text + "'.");
            nodeName = "unknown";
            break;
        default:
            System.out.println("Other node " + node.getNodeType()
                    + " : " + node.getClass());
            break;
        }
    } // doNode()

}
------------------------------ actual output ------------------
inventory.animal.name() = 'Fred'.
inventory.animal.species() = 'Hippo'.
inventory.animal.weight() = '1552'.
inventory.animal.name() = 'Gert'.
inventory.animal.species() = 'Croc'.
-------------------------------- desired output ---------------
inventory.animal.name() = 'Fred'.
inventory.animal.species() = 'Hippo'.
inventory.animal.weight(Kg) = '1552'.
inventory.animal.name() = 'Gert'.
inventory.animal.species() = 'Croc'.
---------------------------------------------------------------

Clues?
Thomas Fritsch - 06 Nov 2006 17:50 GMT
[...]
> -------------------- animals.xml ------------------------
> <inventory>
[quoted text clipped - 9 lines]
> </inventory>
> -------------------- ParseXML.java -----------------------
[...]
>     private static void doNode(Node node, String name) {
>         String nodeName = "unknown";
[quoted text clipped - 26 lines]
>             System.out.println(name + "(" + type + ") = '"
>                                     + text + "'.");
Some thoughts:
(1) You should place the code above (concerning the extraction of the
"type" attribute) not in your Node.TEXT_NODE case, but in your
Node.ELEMENT_NODE case. Reason is that the "type" attribute belongs to
an element-node (the <animal> element), not to a text-node.
(2) You should do something similar (like you do for extracting the
"type" attribute) for extracting the "weight" attribute from an element
node.

>             nodeName = "unknown";
>             break;
[quoted text clipped - 6 lines]
>
> }
[...]
> Clues?

Signature

Thomas

Thomas Fritsch - 06 Nov 2006 18:22 GMT
Thomas Fritsch schrieb:
> (1) You should place the code above (concerning the extraction of the
> "type" attribute) not in your Node.TEXT_NODE case, but in your
[quoted text clipped - 3 lines]
> "type" attribute) for extracting the "weight" attribute from an element
> node.
arrghh! I meant:
(2) ... for extracting the "units" attribute from an element node.
Signature

Thomas

Ian Wilson - 07 Nov 2006 09:21 GMT
> Thomas Fritsch schrieb:
>
[quoted text clipped - 8 lines]
> arrghh! I meant:
> (2) ... for extracting the "units" attribute from an element node.

Thanks Thomas.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.