Results 1 to 8 of 8
Like Tree2Likes
  • 1 Post By eRaaaa
  • 1 Post By Eleeist

Thread: Operations on Nodes

  1. #1
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default Operations on Nodes

    Hi,

    I am trying to learn how to read XML files in Java. I find it really difficult to grasp the structure of the DOM and how to operate on Nodes. I have read tons of tutorials but most provide just the code with litte or no explanation what is happening.

    Here is the XML file I am trying to read:

    Java Code:
    <?xml version="1.0"?>
    <company>
        <staff>
            <firstname>test</firstname>
            <lastname>test2</lastname>
            <nickname>test3</nickname>
            <salary>test4</salary>
        </staff>
        <staff>
            <firstname>test5</firstname>
            <lastname>test6</lastname>
            <nickname>test7</nickname>
            <salary>test8</salary>
        </staff>
    </company>
    And here is the code that supposed to output the firstnames of staff:

    Java Code:
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.io.File;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
    
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder  = factory.newDocumentBuilder();
            Document document = builder.parse(new File("/Users/Eleeist/Desktop/test.xml"));
            
            Element companyElement = document.getDocumentElement();
            
            NodeList elements = companyElement.getElementsByTagName("firstname");
            
            System.out.println(elements.item(0).getNodeValue() + " " + elements.item(1).getNodeValue());
            
        }
    
    }
    However, the output is just "null null".

    Could somebody please explain to me what is happening and what should I do to make it work? :)

    Thanks.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default Re: Operations on Nodes

    Try to get the childnode first:
    System.out.println(elements.item(0).getChildNodes( ).item(0).getNodeValue() + " " + elements.item(1).getChildNodes().item(0).getNodeVa lue());
    or try to use getTextContent
    System.out.println(elements.item(0).getTextContent () + " " + elements.item(1).getTextContent());

    or use XPath :P
    Fubarable likes this.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Operations on Nodes

    I think that a problem is that your XML has many more nodes than you realize. Everything is a Node. To see what I mean, recurse through your XML file and have it print out all of its contents (though I didn't display attributes since your simple file doesn't have any:

    Java Code:
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.io.File;
    
    public class Xml001 {
       private static final String XML_FILE = "/Users/Eleeist/Desktop/test.xml";
       // private static final String XML_FILE = "src/yr12/m02/a/Xml001.xml";
    
       public static void main(String[] args) throws Exception {
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          File xmlFile = new File(XML_FILE);
          Document document = builder.parse(xmlFile);
    
          recurseThru(document, "", 0);
    
          // Element companyElement = document.getDocumentElement();
          // NodeList elements = companyElement.getElementsByTagName("firstname");
          // System.out.println(elements.item(0).getNodeValue() + " "
          // + elements.item(1).getNodeValue());
       }
    
       private static void recurseThru(Node node, String tabs, int level) {
          System.out.println(tabs + "level: " + level);
          System.out.println(tabs + "node:  " + node.getNodeName());
          System.out.println(tabs + "value: " + node.getNodeValue());
          System.out.println(tabs + "text:  " + node.getTextContent());
    
          if (node.hasChildNodes()) {
             tabs = "\t" + tabs;
             level++;
             NodeList nodeList = node.getChildNodes();
             for (int i = 0; i < nodeList.getLength(); i++) {
                Node childNode = nodeList.item(i);
                recurseThru(childNode, tabs, level);
             }
          }
       }
    
    }

  4. #4
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default Re: Operations on Nodes

    Indeed, I have not known that there were so many nodes. I tried aRaaaa advice and it works.

    How would I go about reading elements attributes? Let's say the new XML file looks like this:

    Java Code:
    <?xml version="1.0"?>
    <company>
        <staff>
            <firstname name="test" />
            <lastname>test2</lastname>
            <nickname>test3</nickname>
            <salary>test4</salary>
        </staff>
        <staff>
            <firstname name="test5" />
            <lastname>test6</lastname>
            <nickname>test7</nickname>
            <salary>test8</salary>
        </staff>
    </company>
    And here is the updated code:

    Java Code:
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.io.File;
     
    public class Test {
     
        public static void main(String[] args) throws Exception {
     
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder  = factory.newDocumentBuilder();
            Document document = builder.parse(new File("/Users/Eleeist/Desktop/test.xml"));
             
            Element companyElement = document.getDocumentElement();
             
            NodeList elements = companyElement.getElementsByTagName("firstname");
             
            System.out.println(elements.item(0).getTextContent() + " " + elements.item(1).getTextContent());
             
        }
     
    }

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Operations on Nodes

    Quote Originally Posted by Eleeist View Post
    How would I go about reading elements attributes? Let's say the new XML file looks like this:
    Look up API for Node and check the methods that are available. With this you should be able to figure it out, I'll bet.

  6. #6
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default Re: Operations on Nodes

    Got it:

    Java Code:
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.io.File;
     
    public class Test {
     
        public static void main(String[] args) throws Exception {
     
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder  = factory.newDocumentBuilder();
            Document document = builder.parse(new File("/Users/Eleeist/Desktop/test.xml"));
             
            Element companyElement = document.getDocumentElement();
             
            NodeList elements = companyElement.getElementsByTagName("firstname");
             
            System.out.println(elements.item(0).getAttributes().item(0).getTextContent() + " " + elements.item(1).getAttributes().item(0).getTextContent());
             
        }
     
    }
    Ok, the last thing: going down the levels.

    Let's say I have this:

    Java Code:
    <?xml version="1.0"?>
    <company>
        <staff>
            <deeper>
                <evendeeper>
                    <somevalue>Hey!</somevalue>
                </evendeeper>
            </deeper>
        </staff>
    </company>
    How do I get to my "Hey" text?

    I tried something like this:

    Java Code:
    System.out.println(elements.item(0).getChildNodes().item(0).getChildNodes().item(0)...;
    But I don't think it is the right thing to do (and it does not seem to work).

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Operations on Nodes

    The simplest way to get that (that I know of) is to follow eRaaaaaaaaaaaa's (how many a's?) initial suggestion: use XPath. It's really the best answer to solve you problem.


    This can use your DOM document so much of the code you have can be used with XPath.

  8. #8
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default Re: Operations on Nodes

    I read about XPath and modified one of my classes to use it, and it works :). I will post here if encounter any problems.

    Thanks both of your for suggestions :).
    Fubarable likes this.

Similar Threads

  1. Operations on JList
    By africanhacker in forum AWT / Swing
    Replies: 7
    Last Post: 03-21-2011, 04:15 PM
  2. Date operations
    By SAR in forum New To Java
    Replies: 9
    Last Post: 07-21-2010, 09:13 AM
  3. forcibly terminating io operations
    By arnab321 in forum CLDC and MIDP
    Replies: 2
    Last Post: 11-15-2008, 08:51 PM
  4. Illegal Arithmetic Operations?
    By Cruor in forum New To Java
    Replies: 13
    Last Post: 09-19-2008, 04:46 PM
  5. String operations..
    By sireesha in forum New To Java
    Replies: 4
    Last Post: 12-14-2007, 02:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •