Solved

Java: read xml file

Posted on 2004-08-09
15
2,985 Views
Last Modified: 2008-03-03
I've an XML file:

<?xml version="1.0"?>
<logon>
      <hostname>100.100.00.00</hostname>
      <port>8000</port>
      <dbname>mysql</dbname>
      <user>...</user>
      <password>...</password>
</logon>

...and need a (generic) Java method to read the XML to internal variables. Can you assist?
0
Comment
Question by:go4java
  • 5
  • 4
  • 3
  • +2
15 Comments
 
LVL 9

Expert Comment

by:keteracel
ID: 11752426
you'll probably want to use SAX... i'll post some sample code in a minute:

0
 
LVL 9

Assisted Solution

by:keteracel
keteracel earned 200 total points
ID: 11752539
import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/*
 * Created on 09-Aug-2004 by pl9609
 */

/**
 *
 * @author pl9609
 */
public abstract class DatabaseReader extends DefaultHandler {
    public DatabaseReader(String filename) {
        SAXParserFactory factory = SAXParserFactory.newInstance();

        try {
            // Parse the input
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new File(filename), this);

        }
        catch (Throwable t) {
            System.out.println(
                "Unable to parse the '"
                    + filename
                    + "' file.\n"
                    + t.getClass().getName());
            t.printStackTrace();
            isError = true;
            System.exit(1);
        }
    }

    /*
     *  (non-Javadoc)
     * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    public void startElement(
        String uri,
        String localName,
        String qName,
        Attributes attributes) {

        try {
            if (localName.equals("hostname") || qName.equals("hostname")) {
                status = HOST;
            }
        }
        catch (NullPointerException e) {
              System.out.println("found null pointer!");
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
        throws SAXException {
        if (status == HOST) {
            hostname = (new String(ch, start, length)).trim();
        }
        else if (status == PORT {
            port = (new String(ch, start, length)).trim();
        }
        else if (status == DB {
            db = (new String(ch, start, length)).trim();
        }
        else if (status == USER {
            user = (new String(ch, start, length)).trim();
        }
        else if (status == PASSWD {
            passwd = (new String(ch, start, length)).trim();
        }
    }

    /* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
        throws SAXException {
    }

    public String getHostName() {
        return hostname;
    }

    public String getPort() {
        return port;
    }

    public String getDB() {
        return db;
    }

    public String getUser() {
        return user;
    }

    public String getPasswd() {
        return passwd;
    }

    private String hostname;
    private String port;
    private String db;
    private String user;
    private String passwd;

    private final int NONE = 0;
    private final int HOST = 1;
    private final int PORT = 2;
    private final int DB = 3;
    private final int USER = 4;
    private final int PASSWD = 5;

    private int status = NONE;
}
0
 
LVL 9

Expert Comment

by:keteracel
ID: 11752568
sorry, I didn't finish the startElement or endElement:

    public void startElement(
        String uri,
        String localName,
        String qName,
        Attributes attributes) {

        try {
            if (localName.equals("hostname") || qName.equals("hostname")) {
                status = HOST;
            }
             else if (localName.equals("port") || qName.equals("port")) {
                status = PORT;
            }
             else if (localName.equals("dbname") || qName.equals("dbname")) {
                status = DB;
            }
             else if (localName.equals("user") || qName.equals("user")) {
                status = USER;
            }
             else if (localName.equals("password") || qName.equals("password")) {
                status = PASSWD;
            }
             else {
                status = NONE;
            }
        }
        catch (NullPointerException e) {
             System.out.println("found null pointer!");
            e.printStackTrace();
        }
    }

    public void endElement(String uri, String localName, String qName)
        throws SAXException {
        status = NONE;
    }
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 9

Expert Comment

by:keteracel
ID: 11752597
so to use this parser, use:

DatabaseReader reader = new DatabaseReader("file.xml");

then to get things from it, use:

String hostname = reader.getHostName();
int port = Integer.parseInt(reader.getPort());

etc...
0
 
LVL 9

Expert Comment

by:keteracel
ID: 11752630
using CDATA for integers (like in port) makes things more tricky. A better solution may be to use attributes like so:

<?xml version="1.0"?>
<logon>
     <connection hostname="100.100.00.00" port="8000"/>
     <dbname>mysql</dbname>
     <user>...</user>
     <password>...</password>
</logon>
0
 

Author Comment

by:go4java
ID: 11752688
keteracel, thank you so far.
code looks pretty long - is there a more generic way of reading simple XML (without XSLT) and put the field content to variables?
0
 
LVL 9

Assisted Solution

by:Venci75
Venci75 earned 100 total points
ID: 11753012
XSLT has nothing to do with this.
If you need another aproach - try DOM:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("c:/conf.xml"));

System.out.println(doc.getElementsByTagName("connection").item(0).getAttributes().getNamedItem("hostname").getNodeValue());

System.out.println(doc.getElementsByTagName("dbname").item(0).getFirstChild().getNodeValue());
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 100 total points
ID: 11753179
0
 

Author Comment

by:go4java
ID: 11753224
fine, mayankeagle. can you give the code sample.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11753440
There are plenty of samples on the links that I posted! That's why I didn't paste code. It'll probably increase the size of this page a lot if I paste all that here. You can have a look at those examples as they are sorted by heading/ title. Based on what you want to do, you can look at the example you're interested in.
0
 

Author Comment

by:go4java
ID: 11753492
Sorry, but I did not understand these samples; thats the reason for posting here. Otherwise I can use Google.
0
 

Author Comment

by:go4java
ID: 11753672
That's one of the solutions:

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadXMLFile {

    public void ReadXMLFile(){

        try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("mysql.xml"));

            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

            NodeList listOfLogons = doc.getElementsByTagName("logon");
            int totalLogons = listOfLogons.getLength();
            System.out.println("Total logons : " + totalLogons);

            for(int s=0; s<listOfLogons.getLength() ; s++) {

                    Node firstLogonNode = listOfLogons.item(s);

                    if (firstLogonNode.getNodeType() == Node.ELEMENT_NODE) {

                                Element firstLogonElement = (Element)firstLogonNode;
                                //-------
                                NodeList hostnameList = firstLogonElement.getElementsByTagName("hostname");
                                Element hostnameElement = (Element)hostnameList.item(0);
                                NodeList textHNList = hostnameElement.getChildNodes();
                                System.out.println("hostname : " + (textHNList.item(0)).getNodeValue().trim());
                                //-------
                                NodeList portList = firstLogonElement.getElementsByTagName("port");
                                Element portElement = (Element)portList.item(0);
                                NodeList textPortList = portElement.getChildNodes();
                                System.out.println("port : " + (textPortList.item(0)).getNodeValue().trim());
                                //-------
                                NodeList dbnameList = firstLogonElement.getElementsByTagName("dbname");
                                Element dbnameElement = (Element)dbnameList.item(0);
                                NodeList textDBList = dbnameElement.getChildNodes();
                                System.out.println("dbname : " + (textDBList.item(0)).getNodeValue().trim());
                                        //-------
                                NodeList userList = firstLogonElement.getElementsByTagName("user");
                                Element userElement = (Element)userList.item(0);
                                NodeList textUserList = userElement.getChildNodes();
                                System.out.println("user : " + (textUserList.item(0)).getNodeValue().trim());
                                        //-------
                                NodeList passwordList = firstLogonElement.getElementsByTagName("password");
                                Element passwordElement = (Element)passwordList.item(0);
                                NodeList textPWList = passwordElement.getChildNodes();
                                System.out.println("password : " + (textPWList.item(0)).getNodeValue().trim());
                    }
            }

        } catch (SAXParseException err) {
            System.out.println ("Parsing error: " + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());

        } catch (SAXException e) {
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();

        } catch (Throwable t) {
            t.printStackTrace ();
        }

    }

}



If there is a better way of looping over the structure, pls. let me know.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 100 total points
ID: 11755203
Are you committed to that file format? If not, it's completely trivial to use XMLEn/Decoder to do what you want to do:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.1_01" class="java.beans.XMLDecoder">
 <object class="NetConfig">
  <void property="dbname">
   <string>oracle</string>
  </void>
  <void property="port">
   <int>9000</int>
  </void>
 </object>
</java>

See http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLEncoder.html
http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11759856
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11760897
8-)
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
backtracking recursion  code 19 57
Where to store the queries for modification of table 4 61
tomcat administrtor 12 46
Java: anonymous class 4 17
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…

785 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