Solved

How to read a XML file in JAVA.

Posted on 2011-09-20
10
270 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
[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
  • 4
  • 3
  • 3
10 Comments
 
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
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
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 …
Suggested Courses

626 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