Solved

How to read a XML file in JAVA.

Posted on 2011-09-20
10
254 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
 

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
json format text only 4 65
Printing to a specific printer tray (HP 806dn printer) 3 64
wordlen challenge 3 47
firstChar challenge 13 84
The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

758 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

17 Experts available now in Live!

Get 1:1 Help Now