• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3034
  • Last Modified:

Java: read xml file

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
go4java
Asked:
go4java
  • 5
  • 4
  • 3
  • +2
4 Solutions
 
keteracelCommented:
you'll probably want to use SAX... i'll post some sample code in a minute:

0
 
keteracelCommented:
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
 
keteracelCommented:
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
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
keteracelCommented:
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
 
keteracelCommented:
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
 
go4javaAuthor Commented:
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
 
Venci75Commented:
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
 
go4javaAuthor Commented:
fine, mayankeagle. can you give the code sample.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
go4javaAuthor Commented:
Sorry, but I did not understand these samples; thats the reason for posting here. Otherwise I can use Google.
0
 
go4javaAuthor Commented:
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
 
CEHJCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
CEHJCommented:
8-)
0
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 5
  • 4
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now