Solved

How to read a XML file in JAVA.

Posted on 2011-09-20
10
259 Views
Last Modified: 2012-05-12
Hi,

I need to read an XML file in my JAVA app....

eg.

  <person id="1" name="Deep" age="26" gender="Male">

How do read these values????


Thanks In Advance.
 
0
Comment
Question by:CCBRONET
  • 4
  • 3
  • 3
10 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36565623
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36565631
0
 
LVL 1

Expert Comment

by:stephano12
ID: 36565692
I use xstream for reading and writing XML files. Take a look at http://xstream.codehaus.org/alias-tutorial.html , section Attribute aliasing. If you need a more detailed example ask me.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:CCBRONET
ID: 36565770
@stephano12 is there any other method that can read attribute values from an XML file as show above.
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36565800
@CCBRONET: did you looked at my examples?
0
 
LVL 1

Expert Comment

by:stephano12
ID: 36566296
I will attache an example for you using DomElements:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;


public class XmlAttributeParser {

	static public void main(String[] arg) {
		try {
			BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("Enter XML File name: ");
			String xmlFile = bf.readLine();
			File file = new File(xmlFile);
			if (file.exists()) {
				// Create a factory
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				// Use the factory to create a builder
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(xmlFile);
				// Get a list of all elements in the document
				NodeList list = doc.getElementsByTagName("*");
				System.out.println("XML Elements: ");
				for (int i = 0; i < list.getLength(); i++) {
					// Get element
					Element element = (Element) list.item(i);
					System.out.println(element.getNodeName());
					NamedNodeMap atList = element.getAttributes();
					for (int ind = 0; ind <atList.getLength(); ind ++){
						System.out.println(((Attr) atList.item(ind)).getNodeName() + " / " + ((Attr) atList.item(ind)).getNodeValue());
					}
				}
			} else {
				System.out.print("File not found!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

}

Open in new window

It will show you this:
XML Elements:
person
age / 26
gender / Male
id / 1
name / Deep
0
 

Author Comment

by:CCBRONET
ID: 36578524
Hi Stephano,

What would i need to change to read a particular value like "gender"

Thanks In Advance.
0
 
LVL 1

Accepted Solution

by:
stephano12 earned 500 total points
ID: 36578659
You can get the particular value using:
atList.getNamedItem("gender") in order to get the node, an in order to get the value of the node use atList.getNamedItem("gender").getNodeValue();
public class XmlAttributeParser {

	static public void main(String[] arg) {
		try {
			BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("Enter XML File name: ");
			String xmlFile = bf.readLine();
			File file = new File(xmlFile);
			if (file.exists()) {
				// Create a factory
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				// Use the factory to create a builder
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(xmlFile);
				// Get a list of all elements in the document
				NodeList list = doc.getElementsByTagName("*");
				System.out.println("XML Elements: ");
				for (int i = 0; i < list.getLength(); i++) {
					// Get element
					Element element = (Element) list.item(i);
					System.out.println(element.getNodeName());
					NamedNodeMap atList = element.getAttributes();
					System.out.println(atList.getNamedItem("gender").getNodeValue());
//					for (int ind = 0; ind <atList.getLength(); ind ++){
//						System.out.println(atList.item(ind).getNodeName() + " = " + atList.item(ind).getNodeValue());
//					}
				}
			} else {
				System.out.print("File not found!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

}

Open in new window

0
 

Author Comment

by:CCBRONET
ID: 36910191
Stephano,

I'm receiving my xml file in form of a msg using active MQ

public void onMessage(Message message)
            {
                  if(message instanceof TextMessage)
                  {
                        TextMessage tm = (TextMessage) message;
                        try
                        {
                                    
                                          
                                    System.out.println("~~Received~~: " + tm.getText());                        //All processing done here
                                    XMLTransformations trans = new XMLTransformations();
                                    Node xmlFile = trans.stringToXML(tm.getText());
                                    // Create a factory
                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    // Use the factory to create a builder
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    
                                    Document doc = builder.parse(tm.getText());  //getting error at this line
                                    NodeList list = doc.getElementsByTagName("*");


i am getting an error


~~Received~~: <?xml version="1.0" encoding="UTF-8"?>
<inward amount="3371923.52" branch="400209005" clgDate="2011-07-20" clgNo="1" noIns="211" type="inwardDebitNote" user="sysAdmin1"/>

Error reading message: java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8"?>
<inward amount="3371923.52" branch="400209005" clgDate="2011-07-20" clgNo="1" noIns="211" type="inwardDebitNote" user="sysAdmin1"/>

java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8"?>
<inward amount="3371923.52" branch="400209005" clgDate="2011-07-20" clgNo="1" noIns="211" type="inwardDebitNote" user="sysAdmin1"/>

      at java.net.URL.<init>(Unknown Source)
      at java.net.URL.<init>(Unknown Source)
      at java.net.URL.<init>(Unknown Source)
      at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
      at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
      at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
      at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
      at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
      at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
      at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
      at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
      at com.citizen.cbs.businessservices.messaging.Consumer_1$MyConsumer.onMessage(Consumer_1.java:729)
      at org.apache.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:1229)
      at org.apache.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:134)
      at org.apache.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:205)
      at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:122)
      at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:43)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
com.citizen.cbs.model.dao.MyException: no protocol: <?xml version="1.0" encoding="UTF-8"?>
<inward amount="3371923.52" branch="400209005" clgDate="2011-07-20" clgNo="1" noIns="211" type="inwardDebitNote" user="sysAdmin1"/>

      at com.citizen.cbs.businessservices.messaging.Consumer_1$MyConsumer.onMessage(Consumer_1.java:1281)
      at org.apache.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:1229)
      at org.apache.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:134)
      at org.apache.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:205)
      at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:122)
      at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:43)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
0
 

Author Closing Comment

by:CCBRONET
ID: 37529101
Good Support....
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
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…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

813 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now