Java XML Tree Reading

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
richardsimnettAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
The best way to do this is probably to use XPath

http://javaalmanac.com/egs/org.w3c.dom/xpath_GetAbsElem.html
0
gauravkrtomarCommented:
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
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

seet82Commented:
if you don't mind opensource APIs, you can try this
http://www.castor.org/
0
richardsimnettAuthor Commented:
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
gauravkrtomarCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
richardsimnettAuthor Commented:
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
richardsimnettAuthor Commented:
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
richardsimnettAuthor Commented:
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
objectsCommented:
> import org.apache.xpath.*;

get rid of that line
0
richardsimnettAuthor Commented:
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
objectsCommented:
what version of java are you running? u need 1.5.
0
richardsimnettAuthor Commented:
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
objectsCommented:
import javax.xml.xpath.*;

should cover all those.
0
richardsimnettAuthor Commented:
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
richardsimnettAuthor Commented:
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
objectsCommented:
> 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
richardsimnettAuthor Commented:
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
objectsCommented:
What compiler and compliance is eclipse set to?
0
richardsimnettAuthor Commented:
objects,
Its set to use jre 1.5 and has a compliance level of 5.0.

Thanks,
Rick
0
gauravkrtomarCommented:
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
richardsimnettAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.