Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to read a XML file in JAVA.

Posted on 2011-09-20
10
Medium Priority
?
286 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 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
Independent Software Vendors: 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!

 

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:Gurvinder Pal Singh
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 2000 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

Independent Software Vendors: 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

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…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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 …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

885 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