how to read XML file in Java?
hi
Can anyone tell me how to read XML file?My XML file formate is somehwat like below :
<Root>
<Nodes>
<Node id="1" name="name1" ref="ref1"/>
<Node id="2" name="name2" ref="ref2"/>
</Nodes>
</Root>
How i can read this file? I want to write a function which can give me the value of node. Like ...
String getName("id1") // will return name1
or
String getId("name1") // will return id1
So, depend upnon the value of the node element , it returns the other value of same node.
How i can implement this using JAVA ? Reply ASAP.
Thanks in advance ....
Re: how to read XML file in Java?
Re: how to read XML file in Java?
Well it's been a little while since I've done XML manipulation in Java, but I remember when I did something similar to this, only my source was over a socket instead of from a file, but that should be irrelevant, you'll have to do something like this to turn your XML into a Document type, which can be parsed from there.
Code:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlSchema))); //where xmlSchema is my String
traverseSchema(doc); //my function to parse the state machine represented by XML
So now that you're here, you will have Node and NodeList manipulation, based on what you're looking for. I had many element which had attributes like yours, and I was looking for occurences of them.
But given your structure, say you have your Node (a Node will be in your case, a single one of your Nodes in your example), you could obtain the attributes by
Code:
Node myNode;
... //some extraction of your Node
myNode.getAttributes().getNamedItem("name").getNodeValue(); //returns name1
I should mention that I was using the following classes:
Code:
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
org.w3c.dom.Document;
org.w3c.dom.NamedNodeMap;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
If you're still stuck, just reply I'll see if I can give you a more concrete example if it's required. The Java API describes all this.
Re: how to read XML file in Java?
You can do it two main ways - either with DOM (Document Object Model), which loads the whole XML file as a Document, or with SAX (Simple API for XML), which reads the file and calls into your code with details of each element.
DOM is easier to use for small files, and gives you 'random access' to the elements, but takes a while and a lot of memory to load large files. Sax is a bit fiddly to use, but relatively lightweight and fast, and better suited sequential processing of large files.
See Parse Using SAX or DOM for (limited) examples.
The ability to simplify means to eliminate the unnecessary so that the necessary may speak...
H. Hofmann
Re: how to read XML file in Java?
Quote:
Originally Posted by Deliverance
Well it's been a little while since I've done XML manipulation in Java, but I remember when I did something similar to this, only my source was over a socket instead of from a file, but that should be irrelevant, you'll have to do something like this to turn your XML into a
Document type, which can be parsed from there.
Code:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlSchema))); //where xmlSchema is my String
traverseSchema(doc); //my function to parse the state machine represented by XML
So now that you're here, you will have Node and NodeList manipulation, based on what you're looking for. I had many element which had attributes like yours, and I was looking for occurences of them.
But given your structure, say you have your Node (a Node will be in your case, a single one of your Nodes in your example), you could obtain the attributes by
Code:
Node myNode;
... //some extraction of your Node
myNode.getAttributes().getNamedItem("name").getNodeValue(); //returns name1
I should mention that I was using the following classes:
Code:
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
org.w3c.dom.Document;
org.w3c.dom.NamedNodeMap;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
If you're still stuck, just reply I'll see if I can give you a more concrete example if it's required. The Java API describes all this.
hi,thx a lot for your solution, will try this out and let you know.
I have got many solution on net for nodes like
<a>xyz</a> but in my case i had more than one value : <a id=1 name=n> and some thing like that. for that i was looking for here. And i hope that your code snippet will work for my case.
Re: how to read XML file in Java?
Quote:
Originally Posted by dlorde
You can do it two main ways - either with DOM (Document Object Model), which loads the whole XML file as a Document, or with SAX (Simple API for XML), which reads the file and calls into your code with details of each element.
DOM is easier to use for small files, and gives you 'random access' to the elements, but takes a while and a lot of memory to load large files. Sax is a bit fiddly to use, but relatively lightweight and fast, and better suited sequential processing of large files.
See
Parse Using SAX or DOM for (limited) examples.
The ability to simplify means to eliminate the unnecessary so that the necessary may speak...
H. Hofmann
Thanks for reply, but i have came across this solution before posting this question. But in this , the node is having single value. and in my case node is havingmore than one attribute. So, how can i access multiple attributes using this solution ?
Re: how to read XML file in Java?
Quote:
Originally Posted by ujjvalpandya
Thanks for reply, but i have came across this solution before posting this question. But in this , the node is having single value. and in my case node is havingmore than one attribute. So, how can i access multiple attributes using this solution ?
I posted two possible solutions, so it would be helpful if you said which one you're talking about, but I'm going to assume it's the SAX solution. If you look at the example (or, indeed, the SAX API docs), you'll see that the content handler startElement method callback takes an Attributes parameter. These are the attributes in the current element. You can get the value of an attribute out of the Attributes object like this:
Code:
...
startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attributes) {
...
if ("AnElement".equals(localName) {
String attribute1Value = attributes.getValue("Attribute 1 Name");
String attribute2Value = attributes.getValue("Attribute 2 Name");
...
}
...
}
SAX serializes the XML tree structure, simply calling startElement(..) and endElement(..) for each element.
Today, most software exists, not to solve a problem, but to interface with other software...
I.O. Angell
Re: how to read XML file in Java?
Quote:
Originally Posted by dlorde
I posted two possible solutions, so it would be helpful if you said which one you're talking about, but I'm going to assume it's the SAX solution. If you look at the example (or, indeed, the SAX API docs), you'll see that the content handler startElement method callback takes an Attributes parameter. These are the attributes in the current element. You can get the value of an attribute out of the Attributes object like this:
Code:
...
startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attributes) {
...
if ("AnElement".equals(localName) {
String attribute1Value = attributes.getValue("Attribute 1 Name");
String attribute2Value = attributes.getValue("Attribute 2 Name");
...
}
...
}
SAX serializes the XML tree structure, simply calling startElement(..) and endElement(..) for each element.
Today, most software exists, not to solve a problem, but to interface with other software...
I.O. Angell
hi, thx . will try this out.
Re: how to read XML file in Java?
Quote:
Originally Posted by Deliverance
Well it's been a little while since I've done XML manipulation in Java, but I remember when I did something similar to this, only my source was over a socket instead of from a file, but that should be irrelevant, you'll have to do something like this to turn your XML into a
Document type, which can be parsed from there.
Code:
(xmlSchema))); //where xmlSchema is my String
traverseSchema(doc); //my function to parse the state machine represented by XML
Code:
Node myNode;
... //some extraction of your Node
myNode.getAttributes().getNamedItem("name").getNodeValue(); //returns name1
can you please tell me what exactly your traverseSchema(doc); function does? whats code underlying? and for getting node attribute value u mention one code snippet. So, how i will get NODE element value?
you may be finding my question too silly, but i am really new to this XML READING thing.
and will it traverse node one by one ?because i want find the parent of the given attribute value.
my node structure :
....
<node id="1" name="n1" parent="p1">
<node id="2" name="n2" parent="p2">
......
my function will be like this :
if I pass "n1" it should return the "p1". and if "n2" then "p2" should be returned.
means, on passing the value of one node attribute's value, it should return the value of other attributes value , and that of the same node.
Re: how to read XML file in Java?
Quote:
Originally Posted by ujjvalpandya
can you please tell me what exactly your traverseSchema(doc); function does? whats code underlying? and for getting node attribute value u mention one code snippet. So, how i will get NODE element value?
you may be finding my question too silly, but i am really new to this XML READING thing.
and will it traverse node one by one ?because i want find the parent of the given attribute value.
my node structure :
....
<node id="1" name="n1" parent="p1">
<node id="2" name="n2" parent="p2">
......
my function will be like this :
if I pass "n1" it should return the "p1". and if "n2" then "p2" should be returned.
means, on passing the value of one node attribute's value, it should return the value of other attributes value , and that of the same node.
thx.i got the solution from this :)
Re: how to read XML file in Java?
Quote:
Originally Posted by dlorde
I posted two possible solutions, so it would be helpful if you said which one you're talking about, but I'm going to assume it's the SAX solution. If you look at the example (or, indeed, the SAX API docs), you'll see that the content handler startElement method callback takes an Attributes parameter. These are the attributes in the current element. You can get the value of an attribute out of the Attributes object like this:
Code:
...
startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attributes) {
...
if ("AnElement".equals(localName) {
String attribute1Value = attributes.getValue("Attribute 1 Name");
String attribute2Value = attributes.getValue("Attribute 2 Name");
...
}
...
}
SAX serializes the XML tree structure, simply calling startElement(..) and endElement(..) for each element.
Today, most software exists, not to solve a problem, but to interface with other software...
I.O. Angell
thx.i got the solution from this :)
Re: how to read XML file in Java?
Quote:
Originally Posted by Deliverance
Well it's been a little while since I've done XML manipulation in Java, but I remember when I did something similar to this, only my source was over a socket instead of from a file, but that should be irrelevant, you'll have to do something like this to turn your XML into a
Document type, which can be parsed from there.
Code:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlSchema))); //where xmlSchema is my String
traverseSchema(doc); //my function to parse the state machine represented by XML
So now that you're here, you will have Node and NodeList manipulation, based on what you're looking for. I had many element which had attributes like yours, and I was looking for occurences of them.
But given your structure, say you have your Node (a Node will be in your case, a single one of your Nodes in your example), you could obtain the attributes by
Code:
Node myNode;
... //some extraction of your Node
myNode.getAttributes().getNamedItem("name").getNodeValue(); //returns name1
I should mention that I was using the following classes:
Code:
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
org.w3c.dom.Document;
org.w3c.dom.NamedNodeMap;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
If you're still stuck, just reply I'll see if I can give you a more concrete example if it's required. The Java API describes all this.
thx.i got the solution from this :)
1 Attachment(s)
Re: how to read XML file in Java?
Hi, I recently implemented this for my Chess program that i have been writing on and off whenever i can be bothered.
Fire this code into Eclipse and add the jar file to the classpath.
Code:
package com.al.export;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.al.board.Board;
import com.al.board.Square;
import com.al.game.BlackTeam;
import com.al.game.WhiteTeam;
import com.al.pieces.Bishop;
import com.al.pieces.King;
import com.al.pieces.Knight;
import com.al.pieces.Pawn;
import com.al.pieces.Queen;
import com.al.pieces.Rook;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XMLConverter{
public static boolean saveStringToFile(String fileName, String saveString) {
boolean saved = false;
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
try {
bw.write(saveString);
saved = true;
}
finally {
bw.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return saved;
}
public static String getStringFromFile(String fileName) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(fileName));
try {
String s;
while ((s = br.readLine()) != null) {
//add linefeed back since stripped by readline()
sb.append(s);
sb.append("\n");
}
}
finally {
br.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return sb.toString();
}
public static String convertToXML(Board board) {
XStream xstream = new XStream(new DomDriver());
xstream.setMode(XStream.ID_REFERENCES);
xstream.alias("board", Board.class);
xstream.alias("square", Square.class);
xstream.alias("whiteTeam", WhiteTeam.class);
xstream.alias("blackTeam", BlackTeam.class);
xstream.alias("pawn", Pawn.class);
xstream.alias("rook", Rook.class);
xstream.alias("knight", Knight.class);
xstream.alias("bishop", Bishop.class);
xstream.alias("queen", Queen.class);
xstream.alias("king", King.class);
return xstream.toXML(board);
}
public static Board convertFromXML(String xMLString) {
Board board = null;
XStream xstream = new XStream(new DomDriver());
xstream.setMode(XStream.ID_REFERENCES);
xstream.alias("board", Board.class);
xstream.alias("square", Square.class);
xstream.alias("whiteTeam", WhiteTeam.class);
xstream.alias("blackTeam", BlackTeam.class);
xstream.alias("pawn", Pawn.class);
xstream.alias("rook", Rook.class);
xstream.alias("knight", Knight.class);
xstream.alias("bishop", Bishop.class);
xstream.alias("queen", Queen.class);
xstream.alias("king", King.class);
Object obj = xstream.fromXML(xMLString);
if (obj instanceof Board) {
board = (Board) obj;
}
return board;
}
public static boolean saveBoardToXMLFile(String fileName, Board board) {
return saveStringToFile(fileName, convertToXML(board));
}
public static Board getBoardFromXMLFile(String fileName) {
return convertFromXML(getStringFromFile(fileName));
}
public static boolean saveBoardToSerialFile(String fileName, Board board) {
boolean saved = false;
try {
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oos.writeObject(board);
saved = true;
}
finally {
oos.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return saved;
}
public static Board getBoardFromSerialFile(String fileName) {
Board board = null;
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)));
try {
Object obj = ois.readObject();
if (obj instanceof Board) {
board = (Board) obj;
}
}
finally {
ois.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return board;
}
}
There are obviously references to Pieces, Boards etc. which you would replace with your classes, but I'll leave that to you.
Re: how to read XML file in Java?
I used the xmlbeans project, which is quite quite nice for DOM based parsing
xmlbeans.apache.org