Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Java: read xml file

Posted on 2004-08-09
15
2,993 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 29
jar file executable 12 58
oracle 11g 23 106
Bot application - advice 3 38
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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 will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

839 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