Solved

Java: read xml file

Posted on 2004-08-09
15
2,976 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 9

Expert Comment

by:keteracel
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 100 total points
Comment Utility
0
 

Author Comment

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

Expert Comment

by:mayankeagle
Comment Utility
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
Comment Utility
Sorry, but I did not understand these samples; thats the reason for posting here. Otherwise I can use Google.
0
 

Author Comment

by:go4java
Comment Utility
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
Comment Utility
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:mayankeagle
Comment Utility
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

728 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now