Results 1 to 8 of 8

Thread: Reading an XML file in Java

  1. #1
    Join Date
    Dec 2008
    Posts
    28

    Reading an XML file in Java

    Hello, I have a small problem reading an XML file with Java (using the SAX parser) i use this code

    Code:
    projetdinamv2 package; 
    
    / ** 
    * <p> Title: SAXParserXML </ p> 
    * 
    * <p> Description: Class to read an XML file </ p> 
    * 
    <p> * Copyright: Copyright (c) 2008 </ p> 
    * 
    * <p> Company: </ p> 
    * 
    * @ Author Chetna
    * @ Version 1.0 
    * / 
    / / Parse an XML document with JAVA API SAX 
    
    / / importing the necessary API 
    / / to the analysis of XML 
    import org.xml.sax.SAXParseException; 
    import org.xml.sax .*; 
    org.xml.sax.helpers.DefaultHandler import; 
    javax.xml.parsers.SAXParserFactory import; 
    javax.xml.parsers.ParserConfigurationException import; 
    javax.xml.parsers.SAXParser import; 
    / / to access to files 
    import java.io. *; 
    import java.util.ArrayList; 
    import java.util.Vector; 
    
    public class SAXParserXML extends DefaultHandler 
    ( 
    public SAXParserXML () ( 
    try ( 
    jbInit (); 
    ) Catch (Exception ex) ( 
    ex.printStackTrace (); 
    ) 
    ) 
    
    boolean addAuthor; 
    Author static ArrayList = new ArrayList (); / / dynamic array for storing people 
    
    public static void ParcourXML () 
    ( 
    DefaultHandler handler = new SAXParserXML (); 
    SAXParserFactory factory SAXParserFactory.newInstance = (); 
    try 
    ( 
    String URI = "http://mydomain.com/project/dblpmomo.xml"; 
    SAXParser saxParser = factory.newSAXParser (); 
    saxParser.parse (URI handler); 
    ) 
    catch (Throwable t) 
    (/ / If it was an error during the analysis 
    t.printStackTrace (); 
    System.exit (1); 
    ) 
    ) 
    
    / * Public void error (SAXParseException e) throws SAXParseException 
    ( 
    throw e; 
    ) * / 
    
    public void startDocument () throws SAXException 
    ( 
    System.out.println ( "beginning of the document"); 
    ) 
    
    public void endDocument () throws SAXException 
    ( 
    System.out.println ( "end of document"); 
    ) 
    
    public void startElement (String namespaceURI, String simpleName, String qualifiedName, Attributes attrs) throws SAXException 
    ( 
    String qName = simpleName; 
    
    if ( "". equals (qName)) 
    ( 
    qName = qualifiedName; 
    ) 
    if (qName.equalsIgnoreCase ( "author")) / / check whether or not author tag 
    ( 
    addAuthor = true; 
    ) 
    if (attrs! = null) 
    (/ / Attributes listing 
    if (attrs.getLength ()! = 0) 
    / / System.out.println ( "Parameter for" + + qName ":"); 
    for (int i = 0; i <attrs.getLength () i + +) 
    ( 
    String aName = attrs.getLocalName (i); 
    / / get the name of the attribute 
    if ( "". equals (aName)) 
    ( 
    aName = attrs.getQName (i); 
    ) 
    ) 
    ) 
    ) 
    public void EndElement (String namespaceURI, String simpleName, String qualifiedName) throws SAXException 
    ( 
    NomElement String = simpleName; 
    if (nomElement.equals ("")) 
    ( 
    nomElement = qualifiedName; 
    ) 
    addAuthor = false; 
    ) 
    public static void affichageAuthor () / * to read the table of the elements * / 
    ( 
    System.out.println ( "Displaying the vector table"); 
    for (int i = 0; i <Author.size () i + +) 
    ( 
    System.out.println (Author.get (i)); 
    ) 
    
    ) 
    
    public void characters (char [] ch, int start, int length) throws SAXException 
    ( 
    String string = new String (ch, start, length); 
    chaine.trim string = (); 
    
    if (! chaine.equals ("")) 
    ( 
    ) 
    if (addAuthor) 
    ( 
    Author.add (new String (ch, start, length)) / / add attributes in the table of vector 
    ) 
    ) 
    
    private void jbInit () throws Exception ( 
    ) 
    
    
    ) / / End of class
    allowing me to read my XML file and store my values (authors) in a table the only problem is that once my program is a tag / authors, it does not continue to read XML!! How? please help

  2. #2
    Join Date
    Dec 2008
    Posts
    28

    Re: Reading an XML file in Java

    Code:
    <? xml version = "1.0" encoding = "iso-8859-1"?> 
    <dblp> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/AnnevelinkACFHK95"> 
    Jurgen <author> Annevelink </ author> 
    <author> Rafiul Ahad </ author> 
    Amelia Carlson <author> </ author> 
    Daniel H. <author> Fishman </ author> 
    Michael L. <author> Heytens </ author> 
    William Kent <author> </ author> 
    <title> Object SQL - A Language for the Design and Implementation of Object Databases. </ title> 
    <pages> 42-68 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # AnnevelinkACFHK95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Blakeley95"> 
    <author> José A. Blakeley </ author> 
    <title> OQL [C + +]: Extending C + + with an Object Query Capability. </ title> 
    <pages> 69-88 </ pages> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Blakeley95 </ url> 
    <year> 1995 </ year> 
    </ incollection> 
    <incollection mdate="2004-03-08" key="books/acm/kim95/BreitbartGS95"> 
    Yuri Breitbart <author> </ author> 
    <author> Hector Garcia-Molina </ author> 
    <author> Abraham Silberschatz </ author> 
    <title> Transaction Management in Multidatabase Systems. </ title> 
    <pages> 573-591 </ pages> 
    <booktitle> Modern Database Systems </ booktitle> 
    <crossref> books/acm/Kim95 </ CrossRef> 
    <url> db/books/collections/kim95.html # BreitbartGS95 </ url> 
    <year> 1995 </ year> 
    </ incollection> 
    <incollection mdate="2004-03-08" key="books/acm/kim95/BreitbartR95"> 
    Yuri Breitbart <author> </ author> 
    <author> Tom C. Reyes </ author> 
    <title> Overview of the ADDS System. </ title> 
    <pages> 683-701 </ pages> 
    <booktitle> Modern Database Systems </ booktitle> 
    <crossref> books/acm/Kim95 </ CrossRef> 
    <url> db/books/collections/kim95.html # BreitbartR95 </ url> 
    <year> 1995 </ year> 
    </ incollection> 
    - <incollection mdate="2002-01-03" key="books/acm/kim95/ChristodoulakisK95"> 
    Stavros Christodoulakis <author> </ author> 
    Leonidas Koveos <author> </ author> 
    <title> Multimedia Information Systems: Issues and Approaches. </ title> 
    <pages> 318-337 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # ChristodoulakisK95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/DayalHW95"> 
    <author> Umeshwar Dayal </ author> 
    Eric N. <author> Hanson </ author> 
    <author> Jennifer Widom </ author> 
    <title> Active Database Systems. </ title> 
    <pages> 434-456 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # DayalHW95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/DittrichD95"> 
    Angelika Kotz Dittrich <author> </ author> 
    Klaus R. <author> Dittrich </ author> 
    Where <title> Object-Oriented DBMSs Should Do Better: A Critique Based on Early Experiences. </ title> 
    <pages> 238-254 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # DittrichD95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Garcia-MolinaH95"> 
    <author> Hector Garcia-Molina </ author> 
    <author> Meichun Hsu </ author> 
    <title> Distributed Databases. </ title> 
    <pages> 477-493 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Garcia-MolinaH95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Goodman95"> 
    Nathan Goodman <author> </ author> 
    <title> An Object-Oriented DBMS War Story: Developing a Genome Mapping Database in C ++.</ title> 
    <pages> 216-237 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Goodman95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Kaiser95"> 
    Gail E. <author> Kaiser </ author> 
    <title> Cooperative Transactions for Multiuser Environments. </ title> 
    <pages> 409-433 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Kaiser95 </ url> 
    </ incollection> 
    <incollection mdate="2004-03-08" key="books/acm/kim95/KelleyGKRG95"> 
    William Kelley <author> </ author> 
    Sunit K. <author> Gala </ author> 
    <author> Won Kim </ author> 
    <author> Tom C. Reyes </ author> 
    <author> Bruce Graham </ author> 
    <title> Schema Architecture of the UniSQL / M Multidatabase System </ title> 
    <booktitle> Modern Database Systems </ booktitle> 
    <crossref> books/acm/Kim95 </ CrossRef> 
    <pages> 621-648 </ pages> 
    <year> 1995 </ year> 
    <url> db/books/collections/kim95.html # KelleyGKRG95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/KemperM95"> 
    Alfons Kemper <author> </ author> 
    Guido Moerkotte <author> </ author> 
    <title> Physical Object Management. </ title> 
    <pages> 175-202 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # KemperM95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Kim95"> 
    <author> Won Kim </ author> 
    <title> Introduction to Part 1: Next-Generation Database Technology. </ title> 
    <pages> 5-17 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Kim95 </ url> 
    </ incollection> 
    <incollection mdate="2002-01-03" key="books/acm/kim95/Kim95a"> 
    <author> Won Kim </ author> 
    <title> Object-Oriented Database Systems: Promises, Reality, and Future. </ title> 
    <pages> 255-280 </ pages> 
    <year> 1995 </ year> 
    <booktitle> Modern Database Systems </ booktitle> 
    <url> db/books/collections/kim95.html # Kim95a </ url> 
    </ incollection> 
    </ DBLP>

    Moreover, this is an XML test! XML doing the real approximately 600 MB but when I work with AC makes me an error like: org.xml.sax.SAXParseException: Parser has reached the entity expansion limit "64000" set by the Application. Basically what I want to do is store (in a vector) while the names of the authors, the group by then incollection to work with!
    please thanks in advance

  3. #3
    Join Date
    May 2008
    Posts
    115

    Re: Reading an XML file in Java

    In your view , your code is correct (despite a few snippets of death here or there, that does not change the overall functioning of your class). You will not tell which line the error occurs? (as indicated in the error message, complete with details of the call stack) Once that information is known, some debug you should be able to determine what is the problem. Unfortunately, I can not be more precise, having not run your code.

  4. #4
    Join Date
    Feb 2008
    Posts
    1,852

    Re: Reading an XML file in Java

    J2EE with JRun Configuration

    1. Locate the jvm.config file in the jrun_root\bin directory.
    2. Make a back-up copy of the file.
    3. Open the original jvm.config file for editing.
    4. Add the following option, with the desired limit, to the list of Java arguments:

      -DentityExpansionLimit=100000

      For example:
      # Arguments to VM
      java.args=-server -Xmx512M -DentityExpansionLimit=100000
    5. Save the changes to the file.
    6. Restart the deployed instance(s) of ColdFusion for the change to take effect.
    7. If the error still occurs, increase the value specified in the option.

  5. #5
    Join Date
    Oct 2005
    Posts
    2,393

    Re: Reading an XML file in Java

    This is the simplest way to read data from an XML file into a Java program. I have also included some basic error checking, so you can directly cut-paste this code with a few changes ofcourse. All you have to do is change the XML tags within the program to match those that are present in your XML file.

    XML File
    <book>
    <person>
    <first>Kiran</first>
    <last>Pai</last>
    <age>22</age>
    </person>
    <person>
    <first>Bill</first>
    <last>Gates</last>
    <age>46</age>
    </person>
    <person>
    <first>Steve</first>
    <last>Jobs</last>
    <age>40</age>
    </person>
    </book>
    Program Output
    Root element of the doc is book
    Total no of people : 3
    First Name : Kiran
    Last Name : Pai
    Age : 22
    First Name : Bill
    Last Name : Gates
    Age : 46
    First Name : Steve
    Last Name : Jobs
    Age : 40

    Program Listing
    The Java program to read the above XML file is shown below. Go through the program twice and you will understand all its parts. It may look intimidating at first sight, but believe me its very simple.

    Code:
    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 ReadAndPrintXMLFile{
    
        public static void main (String argv []){
        try {
    
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse (new File("book.xml"));
    
                // normalize text representation
                doc.getDocumentElement ().normalize ();
                System.out.println ("Root element of the doc is " + 
                     doc.getDocumentElement().getNodeName());
    
    
                NodeList listOfPersons = doc.getElementsByTagName("person");
                int totalPersons = listOfPersons.getLength();
                System.out.println("Total no of people : " + totalPersons);
    
                for(int s=0; s<listOfPersons.getLength() ; s++){
    
    
                    Node firstPersonNode = listOfPersons.item(s);
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    
    
                        Element firstPersonElement = (Element)firstPersonNode;
    
                        //-------
                        NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                        Element firstNameElement = (Element)firstNameList.item(0);
    
                        NodeList textFNList = firstNameElement.getChildNodes();
                        System.out.println("First Name : " + 
                               ((Node)textFNList.item(0)).getNodeValue().trim());
    
                        //-------
                        NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                        Element lastNameElement = (Element)lastNameList.item(0);
    
                        NodeList textLNList = lastNameElement.getChildNodes();
                        System.out.println("Last Name : " + 
                               ((Node)textLNList.item(0)).getNodeValue().trim());
    
                        //----
                        NodeList ageList = firstPersonElement.getElementsByTagName("age");
                        Element ageElement = (Element)ageList.item(0);
    
                        NodeList textAgeList = ageElement.getChildNodes();
                        System.out.println("Age : " + 
                               ((Node)textAgeList.item(0)).getNodeValue().trim());
    
                        //------
    
    
                    }//end of if clause
    
    
                }//end of for loop with s var
    
    
            }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 ();
            }
            //System.exit (0);
    
        }//end of main
    
    
    }
    There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.

    source- developerfusion (Kiran Pai)

  6. #6
    Join Date
    Nov 2009
    Posts
    1

    Re: Reading an XML file in Java

    Hi Reegan.

    I understand the Java program to read a XML file.

    I would like to know, how to read a XML from a URL link on the web, just like this one: http://www.w3schools.com/dom/books.xml

    I've been trying something like this:

    URL xmlUrl=new URL(url);
    InputStream in = xmlUrl.openStream();
    Document doc = parse(in);


    public static Document parse (InputStream is) {
    Document ret = null;
    DocumentBuilderFactory domFactory;
    DocumentBuilder builder;

    try {
    domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(false);
    domFactory.setNamespaceAware(false);
    builder = domFactory.newDocumentBuilder();

    ret = builder.parse(is);
    }
    catch (Exception ex) {
    System.err.println("unable to load XML: " + ex);
    }
    System.out.println("PAssou parse");
    return ret;
    }


    I get a java.net.ConnectException: Connection refused
    in the follow instruction:

    InputStream in = xmlUrl.openStream();


    Can you please help me?
    thanks in advance

  7. #7
    Join Date
    Dec 2009
    Location
    Tempe, AZ
    Posts
    1

    Re: Reading an XML file in Java

    You can use the URL in the DocumentBuilder parse method:


    import java.io.File;
    import java.io.FileReader;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    public class XmlBookMain
    {
    public static void main(String[] args)
    {
    try
    {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://www.w3schools.com/dom/books.xml");
    doc.getDocumentElement().normalize();
    System.out.println("Root element " + doc.getDocumentElement().getNodeName());
    NodeList nodeLst = doc.getElementsByTagName("book");

    for (int s = 0; s < nodeLst.getLength(); s++)
    {
    Node fstNode = nodeLst.item(s);

    if (fstNode.getNodeType() == Node.ELEMENT_NODE)
    {
    Element fstElmnt = (Element) fstNode;
    NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("author");
    Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
    NodeList fstNm = fstNmElmnt.getChildNodes();
    System.out.println("Author : " + ((Node) fstNm.item(0)).getNodeValue());
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

  8. #8
    Join Date
    Jul 2011
    Posts
    1

    Re: Reading an XML file in Java

    But the program was showing the same error.Can you please help me

Similar Threads

  1. Problem in reading file in java
    By TechGate in forum Software Development
    Replies: 5
    Last Post: 02-02-2010, 03:05 AM
  2. Reading tables in java.io
    By Miles Runner in forum Software Development
    Replies: 5
    Last Post: 20-01-2010, 10:30 AM
  3. Java For Reading PDF Files
    By Sheenas in forum Software Development
    Replies: 5
    Last Post: 18-01-2010, 09:43 AM
  4. Java reading from a file
    By xqc72 in forum Software Development
    Replies: 1
    Last Post: 20-11-2009, 08:20 AM
  5. Java - Reading from console
    By WinDoWLoCuS in forum Software Development
    Replies: 3
    Last Post: 09-11-2009, 12:18 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,711,635,552.99647 seconds with 17 queries