Showing posts with label read xml in java. Show all posts
Showing posts with label read xml in java. Show all posts

Friday, September 7, 2012

Read XML in Java

First follow this post http://malalanayake.wordpress.com/2012/09/07/write-xml-in-java/

XmlReader.java

[sourcecode language="java"]
package mysamples;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlReader {

private String name;
private String content;
private Map<String, String> nameAttributes = new HashMap<String, String>();
private Map<String, ArrayList<XmlReader>> nameChildren = new HashMap<String, ArrayList<XmlReader>>();

public XmlReader(InputStream inputStream, String rootName) {
this(rootElement(inputStream, rootName));
}

public XmlReader(String filename, String rootName) {
this(fileInputStream(filename), rootName);
}

public XmlReader(String rootName) {
this.name = rootName;
}

private XmlReader(Element element) {
this.name = element.getNodeName();
this.content = element.getTextContent();
NamedNodeMap namedNodeMap = element.getAttributes();
int n = namedNodeMap.getLength();
for (int i = 0; i < n; i++) {
Node node = namedNodeMap.item(i);
String name = node.getNodeName();
addAttribute(name, node.getNodeValue());
}
NodeList nodes = element.getChildNodes();
n = nodes.getLength();
for (int i = 0; i < n; i++) {
Node node = nodes.item(i);
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
XmlReader child = new XmlReader((Element) node);
addChild(node.getNodeName(), child);
}

}
}

public void addAttribute(String name, String value) {
nameAttributes.put(name, value);
}

private void addChild(String name, XmlReader child) {
ArrayList<XmlReader> children = nameChildren.get(name);
if (children == null) {
children = new ArrayList<XmlReader>();
nameChildren.put(name, children);
}
children.add(child);
}

public String name() {
return name;
}

public void setContent(String content) {
this.content = content;
}

public String content() {
return content;
}

public void addChild(XmlReader xml) {
addChild(xml.name(), xml);
}

public void addChildren(XmlReader... xmls) {
for (XmlReader xml : xmls) {
addChild(xml.name(), xml);
}
}

public XmlReader child(String name) {
XmlReader child = optChild(name);
if (child == null) {
throw new RuntimeException("Could not find child node: " + name);
}
return child;
}

public XmlReader optChild(String name) {
ArrayList<XmlReader> children = children(name);
int n = children.size();
if (n > 1) {
throw new RuntimeException("Could not find individual child node: " + name);
}
return n == 0 ? null : children.get(0);
}

public boolean option(String name) {
return optChild(name) != null;
}

public ArrayList<XmlReader> children(String name) {
ArrayList<XmlReader> children = nameChildren.get(name);
return children == null ? new ArrayList<XmlReader>() : children;
}

public String string(String name) {
String value = optString(name);
if (value == null) {
throw new RuntimeException(
"Could not find attribute: " + name + ", in node: " + this.name);
}
return value;
}

public String optString(String name) {
return nameAttributes.get(name);
}

public int integer(String name) {
return Integer.parseInt(string(name));
}

public Integer optInteger(String name) {
String string = optString(name);
return string == null ? null : integer(name);
}

public double doubleValue(String name) {
return Double.parseDouble(optString(name));
}

public Double optDouble(String name) {
String string = optString(name);
return string == null ? null : doubleValue(name);
}

private static Element rootElement(InputStream inputStream, String rootName) {
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(inputStream);

Element rootElement = document.getDocumentElement();
if (!rootElement.getNodeName().equals(rootName)) {
throw new RuntimeException("Could not find root node: " + rootName);
}
return rootElement;
} catch (IOException exception) {
throw new RuntimeException(exception);
} catch (ParserConfigurationException exception) {
throw new RuntimeException(exception);
} catch (SAXException exception) {
throw new RuntimeException(exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
}
}

private static FileInputStream fileInputStream(String filename) {
try {
return new FileInputStream(filename);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}

}
[/sourcecode]


Here I'm Reading the Employee.xml

[sourcecode language="java"]
public static void main(String[] args) {
XmlReader config = new XmlReader("Employee.xml", "employees");

System.out.println("title: " + config.child("employee").content());

for(XmlReader firstname : config.child("employee").children("firstname")){
System.out.println("First Name :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("lastname")){
System.out.println("Last Name :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("age")){
System.out.println("Age :" + firstname.content());
}

for(XmlReader firstname : config.child("employee").children("email")){
System.out.println("Email :" + firstname.content());
}

}
[/sourcecode]

If You need to read something like this kind of xml you can do it in this way

[sourcecode language="java"]
<config>
<title>test</title>
<version
major="1"
minor="2"/>
<roles>
<role name="admin"/>
<role name="user"/>
</roles>
<users>
<user name="joe" password="pass" role="admin"/>
<user name="harry" password="secret" role="user" email="harry@me.com"/>
</users>
<test/>
</config>
[/sourcecode]


[sourcecode language="java"]
public static void main(String[] args) {
Xml config = new Xml("config.xml","config");

System.out.println("title: "+config.child("title").content());

Xml version = config.child("version");
System.out.println("version: "+version.integer("major")+"."+version.integer("minor"));

for(Xml role:config.child("roles").children("role"))
System.out.println("role: name: "+role.string("name"));

for(Xml user:config.child("users").children("user")) {
String email = user.optString("email");
System.out.println(
"user: name: "+user.string("name")+
", password: "+user.string("password")+
", role: "+user.string("role")+
", email: "+(email==null ? "-" : email));
}

System.out.println("test: "+config.option("test"));
}
[/sourcecode]