?
Solved

Java XML Tree Reading

Posted on 2006-04-16
22
Medium Priority
?
385 Views
Last Modified: 2008-01-09
Hello,
I have an XML document loaded a Document object. I need to know how to navigate the tree to read values from it. I cant seem to find any clear documentation on how to do this. Here is the XML document that is loaded.

<?xml version="1.0"?>
<root>
<!-- start of MailPro-LM Configuration -->
     <!-- basic system configuration options -->
     <basic>
          <system_mode>distributor</system_mode>
          <max_smtp_out>25</max_smtp_out>
          <max_retries>3</max_retries>
          <retry_after>10</retry_after>
          <log_path>/root/log.txt</log_path>
          <accounting_type>database</accounting_type>
          <accounting_path>/root/acct.txt</accounting_path>
          <spool_path>/root/spool/</spool_path>
          <mailer_id>1</mailer_id>
          <dns_max_retries>3</dns_max_retries>
          <mta_ip>192.168.1.115</mta_ip>                                                                                    
     </basic>
</root>

So as an example I would want to be able to retrieve root.basic.retry_after or any other values defined within the container.



Worth 500 points.

Thanks,
Rick
0
Comment
Question by:richardsimnett
  • 11
  • 5
  • 3
  • +3
22 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 16463723
The best way to do this is probably to use XPath

http://javaalmanac.com/egs/org.w3c.dom/xpath_GetAbsElem.html
0
 
LVL 2

Expert Comment

by:gauravkrtomar
ID: 16463999
Following is a sample code:-

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.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLParser {
    private static Document document;

    public static void main(String[] argv) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        //factory.setValidating(true);  
        //factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(new File("xyz.xml"));
            //Where xyz.xml is the xml file
           
            //Now the document contains the whole document in tree form
            //u can traverse to any node any time.
            document.getElementById("retry_after").getFirstChild();
           
        } catch (SAXParseException spe) {
            // Error generated by the parser
            System.out.println("\n** Parsing error" + ", line " +
                spe.getLineNumber() + ", uri " + spe.getSystemId());
            System.out.println("   " + spe.getMessage());

            // Use the contained exception, if any
            Exception x = spe;

            if (spe.getException() != null) {
                x = spe.getException();
            }

            x.printStackTrace();
        } catch (SAXException sxe) {
            // Error generated during parsing)
            Exception x = sxe;

            if (sxe.getException() != null) {
                x = sxe.getException();
            }

            x.printStackTrace();
        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
        }
    } // main
}


U can use the DOM parser if the size of the xml is not big. Or else u can definitiley use the XPath support following is the sample code for that :-

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLParser {

    private static Document document;

    public static void main(String[] argv) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        //factory.setValidating(true);  
        //factory.setNamespaceAware(true);
        try {
              DocumentBuilder builder = factory.newDocumentBuilder();
              document = builder.parse(new File("xyz.xml"));
            //Where xyz.xml is the xml file
           
            //Now the document contains the whole document in tree form
            //u can traverse to any node any time using xpath in following manner.
              //
              XPath xpath = XPathFactory.newInstance().newXPath();
              String expression = "root/basic/retry_after";
              Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
           
        } catch (SAXParseException spe) {
            // Error generated by the parser
            System.out.println("\n** Parsing error" + ", line " +
                spe.getLineNumber() + ", uri " + spe.getSystemId());
            System.out.println("   " + spe.getMessage());

            // Use the contained exception, if any
            Exception x = spe;

            if (spe.getException() != null) {
                x = spe.getException();
            }

            x.printStackTrace();
        } catch (SAXException sxe) {
            // Error generated during parsing)
            Exception x = sxe;

            if (sxe.getException() != null) {
                x = sxe.getException();
            }

            x.printStackTrace();
        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
        } catch (XPathExpressionException e) {
                  e.printStackTrace();
            }
    } // main
}


http://www.w3schools.com/xpath/default.asp
A good tutorial to learn XPath expressions.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16464202
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 2

Expert Comment

by:seet82
ID: 16466979
if you don't mind opensource APIs, you can try this
http://www.castor.org/
0
 

Author Comment

by:richardsimnett
ID: 16467180
Ok guys, Im totally confused, none of the code I tried worked (I am using j2sdk 1.5.0_b06 on linux). What exactly I need to be able to do is this... its fairly simply I just dont know what the code should read for it. I have a function called getValue(String path) which should return a string representation of the data requested from the XML document in path. Here is the function as I have it so far... I just dont know what to put in to make (for example) getValue("root/basic/retry_after") return the value associated with it, in this case 10. Here is what I've got so far could someone just fill in the blanks for me?

public String getValue(String key)
      {
            //return the value associated with given XML Path
            String value="";
            try
            {
                    // Get the matching content
                        value = <getTheValueFromXML document cfg>;
            } catch (javax.xml.transform.TransformerException e)
            {
                         System.out.println("there was an error while retrieving the value associated with " + key);
            }
            return value;
      }
0
 
LVL 2

Accepted Solution

by:
gauravkrtomar earned 1600 total points
ID: 16467305
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // factory.setValidating(true);
            // factory.setNamespaceAware(true);
            try {
                  DocumentBuilder builder = factory.newDocumentBuilder();
                  document = builder.parse(new File(key));
                  // Where xyz.xml is the xml file
                  // Now the document contains the whole document in tree form
                  // u can traverse to any node any time using xpath in following
                  // manner.
                  //
                    XPath xpath = XPathFactory.newInstance().newXPath();
                  String expression = "root/basic/retry_after";
                  Node widgetNode = (Node) xpath.evaluate(expression, document,
                              XPathConstants.NODE);
                  value=widgetNode.getFirstChild().getNodeValue());
//See how i am getting the text value coz the text node is the child of the root/basic/retry_after
//10 is not the value of the root/basic/retry_after but the value of the text node that is child of
//the root/basic/retry_after node.
            } catch (SAXParseException spe) {
                  // Error generated by the parser
                  System.out.println("\n** Parsing error" + ", line "
                              + spe.getLineNumber() + ", uri " + spe.getSystemId());
                  System.out.println("   " + spe.getMessage());

                  // Use the contained exception, if any
                  Exception x = spe;

                  if (spe.getException() != null) {
                        x = spe.getException();
                  }

                  x.printStackTrace();
            } catch (SAXException sxe) {
                  // Error generated during parsing)
                  Exception x = sxe;

                  if (sxe.getException() != null) {
                        x = sxe.getException();
                  }

                  x.printStackTrace();
            } catch (ParserConfigurationException pce) {
                  // Parser with specified options can't be built
                  pce.printStackTrace();
            } catch (IOException ioe) {
                  // I/O error
                  ioe.printStackTrace();
            } catch (XPathExpressionException e) {
                  e.printStackTrace();
            }
               return value;
0
 

Author Comment

by:richardsimnett
ID: 16473784
gauravkrtomar,
Ok what should I be importing as java is reporting the following errors when I try to use your code.

Severity      Description      Resource      In Folder      Location      Creation Time      Id
2      The method newInstance() is undefined for the type XPathFactory      config.java      MailProSMTP      line 216      April 17, 2006 7:39:57 PM      2828
2      XPathConstants cannot be resolved      config.java      MailProSMTP      line 217      April 17, 2006 7:39:57 PM      2829
2      XPathExpressionException cannot be resolved to a type      config.java      MailProSMTP      line 219      April 17, 2006 7:39:57 PM      2830

Here is what I have imported:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;  
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.*;
import org.apache.xpath.*;
0
 

Author Comment

by:richardsimnett
ID: 16473808
gauravkrtomar,
I tried the ones you have above but I get the following:

Severity      Description      Resource      In Folder      Location      Creation Time      Id
2      The import javax.xml.xpath cannot be resolved      config.java      MailProSMTP      line 11      April 17, 2006 7:46:57 PM      2831
2      The import javax.xml.xpath cannot be resolved      config.java      MailProSMTP      line 12      April 17, 2006 7:46:57 PM      2832
2      The import javax.xml.xpath cannot be resolved      config.java      MailProSMTP      line 13      April 17, 2006 7:46:57 PM      2833
2      The import javax.xml.xpath cannot be resolved      config.java      MailProSMTP      line 14      April 17, 2006 7:46:57 PM      2834
2      XPath cannot be resolved to a type      config.java      MailProSMTP      line 219      April 17, 2006 7:46:57 PM      2835
2      XPathFactory cannot be resolved      config.java      MailProSMTP      line 219      April 17, 2006 7:46:57 PM      2836
2      XPathConstants cannot be resolved      config.java      MailProSMTP      line 220      April 17, 2006 7:46:57 PM      2837
2      XPathExpressionException cannot be resolved to a type      config.java      MailProSMTP      line 222      April 17, 2006 7:46:57 PM      2838


I am using j2sdk-1.5.0_b06 on linux. \


Thanks,
Rick
0
 

Author Comment

by:richardsimnett
ID: 16473874
gauravkrtomar,
I have also now tried the other package I knew about import org.apache.xpath.*; but it doesn't seem to work with your code (although the package is found unlike the javax.xml.xpath.  I get these errors using that:

Severity      Description      Resource      In Folder      Location      Creation Time      Id
2      The method newInstance() is undefined for the type XPathFactory      config.java      MailProSMTP      line 215      April 17, 2006 8:02:13 PM      2839
2      XPathConstants cannot be resolved      config.java      MailProSMTP      line 216      April 17, 2006 8:02:13 PM      2840
2      XPathExpressionException cannot be resolved to a type      config.java      MailProSMTP      line 218      April 17, 2006 8:02:13 PM      2841

thanks,
Rick
0
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 16473916
> import org.apache.xpath.*;

get rid of that line
0
 

Author Comment

by:richardsimnett
ID: 16473970
objects,
Ok I have removed that line, and put in the import java.xml.xpath.*; line and I still get this:
Severity      Description      Resource      In Folder      Location      Creation Time      Id
2      The import javax.xml.xpath cannot be resolved      config.java      MailProSMTP      line 11      April 17, 2006 8:25:34 PM      2846
2      XPath cannot be resolved to a type      config.java      MailProSMTP      line 215      April 17, 2006 8:25:34 PM      2847
2      XPathFactory cannot be resolved      config.java      MailProSMTP      line 215      April 17, 2006 8:25:34 PM      2848
2      XPathConstants cannot be resolved      config.java      MailProSMTP      line 216      April 17, 2006 8:25:34 PM      2849
2      XPathExpressionException cannot be resolved to a type      config.java      MailProSMTP      line 218      April 17, 2006 8:25:34 PM      2850

thanks,
rick
0
 
LVL 92

Expert Comment

by:objects
ID: 16473977
what version of java are you running? u need 1.5.
0
 

Author Comment

by:richardsimnett
ID: 16473990
objects,
I am running:
javac 1.5.0_06 on linux

These errors are reported in Eclipse, as well as I get these from the command prompt:

[root@localhost MailProSMTP]# javac MailProSMTP.java
./config.java:215: cannot find symbol
symbol  : class XPath
location: class config
                          XPath xpath = XPathFactory.newInstance().newXPath();
                          ^
./config.java:215: cannot find symbol
symbol  : variable XPathFactory
location: class config
                          XPath xpath = XPathFactory.newInstance().newXPath();
                                        ^
./config.java:216: cannot find symbol
symbol  : variable XPathConstants
location: class config
              Node widgetNode = (Node) xpath.evaluate(key, cfg, XPathConstants.NODE);
                                                                ^
./config.java:218: cannot find symbol
symbol  : class XPathExpressionException
location: class config
                } catch (XPathExpressionException e)
                         ^
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
4 errors
[root@localhost MailProSMTP]#


Thanks,
Rick




0
 
LVL 92

Expert Comment

by:objects
ID: 16474016
import javax.xml.xpath.*;

should cover all those.
0
 

Author Comment

by:richardsimnett
ID: 16474029
objects,
Ok I got javac to compile this without errors, however, when I run the resulting code I get this:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
        The import javax.xml.xpath cannot be resolved
        XPath cannot be resolved to a type
        XPathFactory cannot be resolved
        XPathConstants cannot be resolved
        XPathExpressionException cannot be resolved to a type

        at config.<init>(config.java:11)
        at MailProSMTP.main(MailProSMTP.java:10)

Thanks,
Rick
0
 

Author Comment

by:richardsimnett
ID: 16474031
This is the exact version info as reported by the jvm:

[root@localhost MailProSMTP]# java -version
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
0
 
LVL 92

Expert Comment

by:objects
ID: 16474044
> Ok I got javac to compile this without errors, however, when I run the resulting code I get this:

That error is saying that it wasn't successfully compiled.
0
 

Author Comment

by:richardsimnett
ID: 16474051
objects,
I realize that... all Im saying is that javac didnt report any errors the second time around, after deleting all the existing class files. Im not sure what to do now... the apache.xpath thing seems to be found but the code isnt compatible with it... so I really am still at square one I suppose.

Thanks,
Rick
0
 
LVL 92

Expert Comment

by:objects
ID: 16474070
What compiler and compliance is eclipse set to?
0
 

Author Comment

by:richardsimnett
ID: 16474155
objects,
Its set to use jre 1.5 and has a compliance level of 5.0.

Thanks,
Rick
0
 
LVL 2

Expert Comment

by:gauravkrtomar
ID: 16475478
Hi Rick,
Sorry for the delay, i wasn't able to get mails during the week-end. Are u sure that u only have the following imports, coz it might happen that while importing few imports are ambiguous.

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLParserXPath {

      private static Document document;

      public static void main(String[] argv) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // factory.setValidating(true);
            // factory.setNamespaceAware(true);
            try {
                  DocumentBuilder builder = factory.newDocumentBuilder();
                  document = builder.parse(new File("xyz.xml"));
                  // Where xyz.xml is the xml file

                  // Now the document contains the whole document in tree form
                  // u can traverse to any node any time using xpath in following
                  // manner.
                  //
                  XPath xpath = XPathFactory.newInstance().newXPath();
                  String expression = "root/basic/retry_after";
                  Node widgetNode = (Node) xpath.evaluate(expression, document,
                              XPathConstants.NODE);
                  System.out.println(widgetNode.getFirstChild().getNodeValue());

            } catch (SAXParseException spe) {
                  // Error generated by the parser
                  System.out.println("\n** Parsing error" + ", line "
                              + spe.getLineNumber() + ", uri " + spe.getSystemId());
                  System.out.println("   " + spe.getMessage());

                  // Use the contained exception, if any
                  Exception x = spe;

                  if (spe.getException() != null) {
                        x = spe.getException();
                  }

                  x.printStackTrace();
            } catch (SAXException sxe) {
                  // Error generated during parsing)
                  Exception x = sxe;

                  if (sxe.getException() != null) {
                        x = sxe.getException();
                  }

                  x.printStackTrace();
            } catch (ParserConfigurationException pce) {
                  // Parser with specified options can't be built
                  pce.printStackTrace();
            } catch (IOException ioe) {
                  // I/O error
                  ioe.printStackTrace();
            } catch (XPathExpressionException e) {
                  e.printStackTrace();
            }
      } // main
}

The above is the code that i am able to compile and run.

on command prompt i typed: javac -version
javac: 1.5.0_06

and the javax.xml.XPath is there from jdk1.4.2....so i dont think it is coz of jdk version.... There should be something else. Try checking the compiler version.
0
 

Author Comment

by:richardsimnett
ID: 16482283
gauravkrtomar / objects,
I got it to finally go by re-installing java 1.5.0... I dont know what was wrong with the last install but everything works. Thanks for all your help. I am going to split points.

Thanks,
Rick
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month15 days, 16 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question