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.
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.
This thread is for discussions of A simple way to read an XML file in Java.
hi all
i just started with 'a simple way read an xml file with java', i used the sample program"ReadAndPrintXMLFile" , after compiling i tried to run it , but i get the error saying.
"Parsing error, line 1, uri file:/root/rep/book.xml
XML declaration may only begin entities."
both the java file and xml file are in same dir.,
could anybody tell me whats wrong
thnks.
<graph>
<node>
<id></id>
<label></lable>
<description></description>
</node>
<influence>
<id></id>
<property></property>
<victim_id></victim_id>
</influence>
</graph>
Can somebody help me with this?? This is due in a couple of days, so any quick replies would be EXTREMELY APPRECIATED. thank you very much in advance.
Goodmorning everybody...
I need to convert one XML file into a standard XML file. which means..
We receive a raw XML file from my customer( this data could be from MSAccess, SQL database,.....etc) and this XML file has to be converted into a predefined standard XML format. So that when we upload this standard XML format to SAPBusinessOne tool, it will accepts the data.
I would be lucky, If anybody can give an idea of 'How to convert the raw xml file to a standard XML file ' and what sort software I need to install. ??'
Waiting for your reply...
Thanks in advance....
Kondal
Could someone suggest as to how i should handle this problem. Either mail me at eddyed911@yahoo.com or just post the reply here
Thank YOu
ED
Hi ,
i have a problem...
iam having a xml file having the following structure..
i need to convert this xml file to HTML file having the table of information..
so plz help me out...how to read this in java and have to send the string buffer along with the response.....
<ROOT>
<ROW Name="Product Name~B" CheckBox="" Type="PerformanceNormal"
Count="1" ChildCount="1" Show="Y" Refine="B">
<COL Page="0" Image="" ProductID=""/>
<COL Page="1" Image="" ProductID="3">Sainsbury's aromatherapy
citrus mint</COL>
<COL Page="1" Image="" ProductID="4">TestPerf</COL>
<COL Page="1" Image="" ProductID="5">TestPerf001</COL>
<COL Page="1" Image="" ProductID="24">Ashraf Product</COL>
<COL Page="2" Image="" ProductID="25">Acb</COL>
</ROW>
<ROW Name="Region~H" CheckBox="" Type="PerformanceNormal" Count="2"
ChildCount="1" Show="Y" Refine="H">
<COL Page="0" Image="" ProductID=""/>
<COL Page="1" Image="" ProductID="3">Western Europe</COL>
<COL Page="1" Image="" ProductID="4">Western Europe</COL>
<COL Page="1" Image="" ProductID="5">Western Europe</COL>
<COL Page="1" Image="" ProductID="24">Central and Eastern Europe</COL>
<COL Page="2" Image="" ProductID="25">Central and Eastern Europe</COL>
</ROW>
<ROW Name="Country~H" CheckBox="" Type="PerformanceNormal"
Count="3" ChildCount="1" Show="Y" Refine="H">
<COL Page="0" Image="" ProductID=""/>
<COL Page="1" Image="" ProductID="3">United Kingdom</COL>
<COL Page="1" Image="" ProductID="4">Belgium</COL>
<COL Page="1" Image="" ProductID="5">Belgium</COL>
<COL Page="1" Image="" ProductID="24">Czech Republic</COL>
<COL Page="2" Image="" ProductID="25">Czech Republic</COL>
</ROW>
</ROOT>
Thanks
Kranti Kiran Kumar Parisa
Hi,
I am to raed the xml file with this but prob when i am going to read a large amount of data then it is giving out of memory pls tell me solution
Manuj
The example given by Kiran is cool. But I do have a question.
What if there is a tag in the first name or Last Name such as
<FName>Peter <b>pan</b></FName>
How do you read this value then?
hi!
i'm really interested in xmls...
how do i get the libraries?
from where do i get to download these??
i hope u can help me..
i'm really desperate..
Hi,
How can I add the validating issue to this example ?
I have both xml and xsd files, and I need to validate with the xsd file.
Thanks
Hi,
I am very new to java. I want to import data from XML using java, so i used this code but when i save it i get error in
import javax.xml.parser.documentBuilderFactory
as class javax.xml.parser.documentBuilderFactory not found in import
and also in
import javax.xml.parser.documentBuilder , as
class javax.xml.parser.documentBuilder not found in import.
These are the two errors i am getting. Pls give me the way out.
Thanks,
Meghna.
i want to update the below code of a Dom parser so that it can read all the tag names and the content of a tags of any XML file
and display them on the command prompt.
plz reply as soon as possible.
thanks
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("test.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("channel");
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
}
hi
i m really pleased by reading ur code to read XML file...can u also send me a code to generate xml file at my mailing address
reply me asap
bhavesh
Hi There
the code you have given for xml parsing is really superb can you give me a generic code for parsing any xml file given i will be really thankfull if you can mail me that code at deepsingh_mca@yahoo.com
I have a XML doc like this....
*****************************************************
<table>
<rec>
<field1>abcd</field1>
<field2>xyz</field2>
</rec>
<rec>
<field1></field1>
<field2>kio</field2>
</rec>
</table>
******************************************************
When I use your code with some modifications, the first record is displayed correctly, but the second record doesn't appear.
Also, When I use wordpad to view the contents of XML file, it shows me the exact contents, but when i try to view the content using explorer, in the second rec field, where the value is not there, it shows
<field1 />
instead of <field1></field1>
Can you tell me why this is happening and how can I read a "null" value.
Thank you for such a clear and concise example. I used this to base an XML mining applicaton. Did not need so much of the nesting feature for my particular input, but your code had the following surprises for me. Before using your sample: NodeList - my code wouldn't let me instantiate an abstract class! Element - I had problems casting from Node Document - My parseXmlFile() args and return were incorrect. Thanks again, Richard
Check your null value.
Assump that you have null value in Age tag <Age></Age>
NodeList textAgeList = ageElement.getChildNodes();
if (textAgeList.getLength() == 0) {
System.out.print("Age : Need more infor of Age \n");
} else {
System.out.println("Age : " +
((Node) textAgeList.item(0)).
getNodeValue().trim());
}
Hi,
On a similar theme, how would you handle if the node is not actually present in the XML as in the second person below as I'm currently getting an exception from this?
Do you have to wrap a try/catch around each retrieve from of a node?
e.g.
<Person>
<first>Mark></first>
<last>Thomas</last>
<age>36</age>
</Person>
<Person>
<first>Fred></first>
<last>Bloggs</last>
</Person>
Thanks,
Mark Thomas
Hello Mark,
If you have found a solution to your above problem please send me the code. I shall be eagerly waiting.
Many thanks,
Prakash
Someone please send me code to read the following using Kiran's code
<Fruit>
<Type>Apple</Type>
<Type>Orange</Type>
<Type>Peach</Type>
</Fruit>
Thanks,
Prakash
Hi,
Thank you for your code. I want to read an XML document that is having different child tags. Here you are using the same name for all the childs. I need the code for reading an XML document that is having differnt child nodes.
For example, consider the following code snippet
<Author>
- <Request>
<Name>
<Book>
</Request>
-<Collection>
<Colletion_Name>
. ...</Collection>
</Author>
Could you please send me the code for this.It will be very helpful for me.
Thanks in advance.
Regards,
Dhanaprabhu
Hi All,
How to read an XML data by giving a particular tag name as input.
Regards,
Dhana
How can I retrieve the elements from nested tags. like
<shop>
<book>
<subject>
<author>Something</author>
</subject>
</book>
</shop>
Thanks & Regards
AbdulMajid
Its realy nice, i have been searching for that code, now i got it, thanks a lot, and i have one question, how to read an XML data in ejb? any body can help me, plz send to my mail : sainathgowd@gmail.com, thanks advance.
Regards
Sai.
this is a code written in XML and now i want to read this code in java
so please help me
<?xml version="1.0" encoding="UTF-8"?>
<descriptor>
<file>
<name>simple.txt</name>
<type>TXT</type>
<delimiter></delimiter>
</file>
<table>
<name>simple</name>
</table>
<fields>
<field>
<name>Date</name>
<type>date</type>
<size>8</size>
<begin_offset>0</beginoffset>
<end_offset>8</end_offset>
</field>
<field>
<name>Phone</name>
<type>char</type>
<size>10</size>
<begin_offset>8</beginoffset>
<end_offset>18</end_offset>
</field>
</fields>
</descriptor>
Thanks
Mayank
a good way u introduces but
dear friend
i have problem to solve this matter plz help me or any body else who know can also mail me on capricorn_4all@hotmail.com
i have to make a simple window/frame using java swing and create menus at runtime as described in xml document. XML document is attached below i have needed to load and read xml document using Java API xml. This xml document contains the menus structure.
When we run the application and pass the xml document name using command line argument then the output should contain a window/frame on the screen and create menus as described in the xml document. If we change any menu settings in xml document. Then application should able to recreate menus according to the change.
Note:
1. Use java API for xml processing
2. Xml document passed as command line argument
All menus will be created at run time as described in the xml document
The xml file with code is as under for your kind consideration.
so dear if any body can help me so plz mail me with code/help as soon as possible
With the above line of instructions may i have able to read xml but still not able to create runtime menus by using swing and my desired xml file. plz help me as soon as possible i ll b thank full to u.
The xml code that i have to use is:
<?xml version="1.0" encoding="UTF-8"?>
<!-- New document created at Sun Dec 11 20:59:54 GMT+03:00 2005 -->
<!-- Created by abc -->
<console>
<menus type='Main'>
<menu name='File'>
<menuitem name='New' />
<menuitem name='Open' />
<menuitem name='Close' />
<menuitem name='Exit' />
</menu>
<menu name='Search'>
<menuitem name='Find' />
<menuitem name='Find Next' />
<menuitem name='Replace' />
</menu>
<menu name='Help'>
<menuitem name='Index' />
<menuitem name='About' />
</menu>
</menus>
<menus type='Popup'>
<menuitem name='Cut' />
<menuitem name='Copy' />
<menuitem name='Paste' />
<menuitem name='Find' />
</menus>
</console>
I got all this code from a book and it doesn't work right. When I run the application file it gives me a stack trace bser. Did I do something wrong in the code or what? Oh and btw, yes there are other files associated with this but didn't want to list ALL the code since I figure the error's in here.
import java.util.*;
import java.io.*;
import javax.xml.stream.*; //StAX API
//mine!
public class ProductXMLFile implements ProductDAO
{
private String productsFilename = "products.xml";
private File productsFile = null;
public ProductXMLFile()
{
productsFile = new File(productsFilename);
}
private void checkFile() throws IOException
{
//if the file doesn't exist, create it
if(!productsFile.exists())
productsFile.createNewFile();
}
private boolean saveProducts(ArrayList<Product> products)
{
//creates the XMLOutputFactory object
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
try
{
//check the file to make sure it exists
this.checkFile();
//creates XMLStreamWriter object
FileWriter fileWriter = new FileWriter(productsFilename);
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
//write the products to the file
/*writer.writeStartDocument("1.0");
writer.writeStartElement("Products");
for (Product p : products)
{
writer.writeStartElement("Product");
writer.writeAttribute("Code", p.getCode());
writer.writeStartElement("Description");
writer.writeCharacters(p.getDescription());
writer.writeEndElement();
writer.writeStartElement("Price");
double price = p.getPrice();
writer.writeCharacters(Double.toString(price));
writer.writeEndElement();
writer.writeEndElement();
}
writer.writeEndElement();
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
catch(XMLStreamException e)
{
e.printStackTrace();
return false;
}
return true;*/
}
public ArrayList<Product> getProducts()
{
ArrayList<Product> products = new ArrayList<Product>();
Product p = null;
//creates the XMLInputFactory object
/*XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try
{
//check the file to make sure it exists
this.checkFile();
//creates a XMLStreamReader object
FileReader fileReader = new FileReader(productsFilename);
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);
//read the products from the file
while(reader.hasNext())
{
int eventType = reader.getEventType();
switch(eventType)
{
case XMLStreamConstants.START_ELEMENT:
String elementName = reader.getLocalName();
if(elementName.equals("Products"))
{
p = new Product();
String code = reader.getAttributeValue(0);
p.setCode(code);
}
if(elementName.equals("Description"))
{
String description = reader.getElementText();
p.setDescription(description);
}
if(elementName.equals("Price"))
{
String priceString = reader.getElementText();
double price = Double.parseDouble(priceString);
p.setPrice(price);
}
break;
case XMLStreamConstants.END_ELEMENT:
elementName = reader.getLocalName();
if(elementName.equals("Product"))
{
products.add(p);
}
break;
default:
break;
}
reader.next();
}*/
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
catch(XMLStreamException e)
{
e.printStackTrace();
return null;
}
return products;
}
public Product getProduct(String code)
{
ArrayList<Product> products = this.getProducts();
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean deleteProduct(Product p)
{
ArrayList<Product> products = this.getProducts();
products.remove(p);
return this.saveProducts(products);
}
public boolean addProduct(Product p)
{
ArrayList<Product> products = this.getProducts();
products.add(p);
return this.saveProducts(products);
}
public boolean updateProduct(Product newProduct)
{
ArrayList<Product> products = this.getProducts();
//get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
//add the updated product
products.add(i, newProduct);
return this.saveProducts(products);
}
}
can you post another one that shows how to write the document ?
Hi,
I am a beginner in JAVA technologes. Do we have any sample generic Java implementation which can read any valid XML files?
In this example you mentioned, program reads the XML file and in JAVA program you should have corresponding fields same as xml nodes( Say price or name).
I am looking for an example whch will have a loop to read all nodes in any xml files (any XML file, and each xml can have different element form other xml) and output data to a file/create a runtime classes/store to database. I want to create a generic class for that and not with specific fileds.
Please suggest any article/book for above example.
Here's a really simple way to achieve basic XML parsing. Requires only a couple of lines of code to parse a file like the one in the article.
http://stuffnwotnot.blogspot.com/2009/05/simple-way-to-parse-xml-in-java-2.html
!--removed tag-->Thanks for the post .. very helpful!
!--removed tag-->i want to read an xml file in java and its contents should be stored in a mysql database. does any one helpout by providing the source code
!--removed tag-->Hi all, I have an xml file using by a server. Now i want to update this file when it's still used by the server. Can I do this and how can i do this. The server is the java open source server. I had try to write an jsp page that using to update this xml file but i got an error "java.io.FileNotFoundException: C:\Program Files\geoserver\webapps\geoserver\qltaxi\gml\point.xml (The requested operation cannot be performed on a file with a user-mapped section open)". Could anyone give a solution to solve this. Many thanks.
!--removed tag-->