Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Java: read xml file

Posted on 2004-08-09
15
Medium Priority
?
3,024 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
[X]
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
  • 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 600 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
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 300 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 300 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 300 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 86

Expert Comment

by:CEHJ
ID: 11760897
8-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses

705 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