Solved

How to read a XML file in JAVA.

Posted on 2011-09-20
10
257 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse formatting 6 73
Convert Oracle data into XML document 2 59
VB Script to add site to Java Exception List 4 53
Way to decrease size of apk file 9 45
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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…

895 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

19 Experts available now in Live!

Get 1:1 Help Now