Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Friday, September 7, 2007

Object Serialization with XMLEncoder

Java API provides XMLEncoder class as an alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. For example, the following fragment can be used to create a textual representation the supplied JavaBean and all its properties.

XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
e.writeObject(new JButton("Hello, world"));
e.close();

The XMLEncoder class provides a default denotation for JavaBeans in which they are represented as XML documents complying with version 1.0 of the XML specification and the UTF-8 character encoding of the Unicode/ISO 10646 character set.

The XML syntax uses the following conventions:

  • Each element represents a method call.
  • The "object" tag denotes an expression whose value is to be used as the argument to the enclosing element.
  • The "void" tag denotes a statement which will be executed, but whose result will not be used as an argument to the enclosing method.
  • Elements which contain elements use those elements as arguments, unless they have the tag: "void".
  • The name of the method is denoted by the "method" attribute.
  • XML's standard "id" and "idref" attributes are used to make references to previous expressions - so as to deal with circularities in the object graph.
  • The "class" attribute is used to specify the target of a static method or constructor explicitly; its value being the fully qualified name of the class.
  • Elements with the "void" tag are executed using the outer context as the target if no target is defined by a "class" attribute.
  • Java's String class is treated specially and is written Hello, world where the characters of the string are converted to bytes using the UTF-8 character encoding.


The below code is a sample student bean class to demonstrate the Usage of XMLEncoder and XMLDecoder

Code:

import java.util.Date;

public class Student
{
private String name;
private int age;
private int [] marks_M_P_C;
private String fatherName;
private int rollNumber;
private Date joinDate;

public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public int [] getMarks_M_P_C() {
return marks_M_P_C;
}
public void setMarks_M_P_C(int[] marks_M_P_C) {
this.marks_M_P_C = marks_M_P_C;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}

public double getAvg(){
return (double)(this.getTotal()/3.0);
}

public double getTotal(){
return (double)(this.marks_M_P_C[0]+this.marks_M_P_C[1]+this.marks_M_P_C[2]);
}

public String toString() {
return getClass().getName() +
"[Marks=" + asString(marks_M_P_C) +
",avg=" + getAvg() +
",name=" + name +
",fatherName=" + fatherName +
"rollNumber" + rollNumber +
"age" + age + "]";
}

private String asString(int[] array) {
StringBuffer buffer = new StringBuffer("[");
for (int i=0, n=array.length; i < n; i++) {
if (i != 0) {
buffer.append(",");
}
buffer.append(array[i]);
}
buffer.append("]");
return buffer.toString();
}
}

The below code demonstrate the usage of XmlEncoder to store the object as well as XMLDecoder to Retrieve the object
Code:

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

public class XmlObjTest {
public static void main (String args[]) throws Exception {
Student student = new Student();
student.setMarks_M_P_C(new int[] {146, 52, 53});
student.setName("Hari");
student.setJoinDate(new Date());
student.setRollNumber(1219);
student.setFatherName("Rao");
student.setAge(19);
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("student.xml")));
encoder.writeObject(student);
encoder.close();

System.out.println(student);

XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("student.xml")));
Student studentR = (Student)decoder.readObject();
decoder.close();
System.out.println(studentR);

}
}

The below show how an Object will be stored

Code: (student.xml)

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_08" class="java.beans.XMLDecoder">
<object class="temp.Student">
<void property="age">
<int>19</int>
</void>
<void property="fatherName">
<string>Rao</string>
</void>
<void property="joinDate">
<object class="java.util.Date">
<long>1189158030890</long>
</object>
</void>
<void property="marks_M_P_C">
<array class="int" length="3">
<void index="0">
<int>146</int>
</void>
<void index="1">
<int>52</int>
</void>
<void index="2">
<int>53</int>
</void>
</array>
</void>
<void
property="name">
<string>Hari</string>
</void>
<void
property="rollNumber">
<int>
1219</int>
</void>
</object>
</java>

Tuesday, September 4, 2007

Mapping XML- JavaBean

XML makes data portable. The Java platform makes code portable. The Java APIs for XML make it easy to use XML. Put these together, and you have the perfect combination: portability of data, portability of code, and ease of use. In fact, with the Java APIs for XML, you can get the benefits of XML with little or no direct use of XML.The portability and extensibility of both Java and XML make them ideal choices for the flexibility and wide availability requirements of Web applications and services.

The BeanXMLMapping component converts a JavaBean to an XML document and vice versa. By using JavaBean introspection, XML parsers, and DOM APIs, you can develop this component with a bean2Xml() method to represent the received bean as an XML document and a xml2Bean() method to instantiate and populate the proper bean according to the XML document received.

The below code shows a possible implementation for the BeanXMLMapping component. This particular implementation usesthe JOX (Java Objects in XML) library.

Download Dependencies:

jox116.jar
dtdparser121.jar

Code:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanOutputStream;

public class BeanXMLMapping {

/**
* Method to generate the Bean object for the given xml String
*/
public static Object xml2Bean(String xml, Class className)
{
ByteArrayInputStream xmlData = new ByteArrayInputStream(xml.getBytes());
JOXBeanInputStream joxIn = new JOXBeanInputStream(xmlData);

try{
return (Object) joxIn.readObject(className);
} catch (IOException exc)
{
exc.printStackTrace();
return null;
}
finally{
try{
xmlData.close();
joxIn.close();
} catch (Exception e){
e.printStackTrace();
}
}

}


/**
* Method to generate the XML document String for the received bean
*/
public static String bean2Xml(Object bean)
{
ByteArrayOutputStream xmlData = new ByteArrayOutputStream();
JOXBeanOutputStream joxOut = new JOXBeanOutputStream(xmlData);
try{
joxOut.writeObject(beanName(bean), bean);
return xmlData.toString();
}
catch
(IOException exc){
exc.printStackTrace();
return null;
}
finally{
try{
xmlData.close();
joxOut.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}

/**
* Method to retrieve the Class name for the given bean object
*/
private static String beanName(Object bean){
String fullClassName = bean.getClass().getName();
String classNameTemp = fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length());
return classNameTemp.substring(0, 1)+ classNameTemp.substring(1);
}
}


The BeanXMLMapping class converts a JavaBean to and from an XML document and provides two methods:

bean2Xml(): generates the respective XML document String for the bean instance
xml2Bean(): creates a bean instance for the XML document String


The below Code shows How to use the BeanXMLMapping class to map the bean to xml and vice varsa.

Code:

public class PersonBean {
private String name;
private Integer age;
private Double salary;
private Integer exp;

public PersonBean(){
this.name="test";
this.age=24;
this.salary=5000.0;
this.exp=2;
}

public PersonBean(String name,Integer age,Double salary,Integer exp){
this.name=name;
this.age=age;
this.salary=salary;
this.exp=exp;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getExp() {
return exp;
}
public void setExp(Integer exp) {
this.exp = exp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String toXML(){
return BeanXMLMapping.bean2Xml(this);
}
public static Object fromXML(String xml){
return (PersonBean) BeanXMLMapping.xml2Bean(xml,PersonBean.class);
}
}


Test Code:

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonBean bean=new PersonBean();
String xmlStr=bean.toXML();
System.out.println(xmlStr);
}
}


The Above Test Code Generates the Output As:

<?xml version="1.0" encoding="ISO-8859-1"?>
<PersonBean>
<age>24</age>
<exp>2</exp>
<name>test</name>
<salary>5000.0</salary>
</PersonBean>

Wednesday, August 22, 2007

Working with Online xml

Some times we required to access the xml files which are present at online or working with another site it is required to access the data through the xml.This artical deals how to work with online xml file.The below sample code parse the xml file throuth the given URL String and returns the DOM Document.Then we can access the xml file using that document.

Code:

import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMProvider{
public Document getDocument(String strUrl)throws Exception{
URL url=new URL(strUrl);
InputStream in=url.openStream();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(in);
return document;
}
}

After getiing the document from getDocument() if you want to get retrive entire node list that can be done by
NodeList nodeList=document.getElementsByTagName("NameofTheNode");

By these all the node will come in that Node List.If you want to retrive the attributes with in that Node,that can be done by
Node node= nodeList.item(indx);
NamedNodeMap attrs=node.getAttributes();
String value=nnm.getNamedItem("AttributeNamewithinthatNode").getNodeValue();

Sample Work:

http://www.w3schools.com/xml/note.xml is in the form of










to work with the above xml as:


Code:

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Test{
public static void main(String[] args)throws Exception{
DOMProvider test=new DOMProvider();
Document doc=test.getDocument("http://www.w3schools.com/xml/note.xml");
Node node=doc.getDocumentElement();
System.out.println("Root Node: "+node.getNodeName());
NodeList list=node.getChildNodes();
int childsLen=list.getLength();
for(int index=0;index
Node tag=list.item(index);
if(tag.getNodeType()==Node.ELEMENT_NODE){
NodeList val=tag.getChildNodes();
int vallen=val.getLength();
System.out.println("Tag Name: "+tag.getNodeName());
for(int i=0;i
if(val.item(i)!=null)
System.out.println("Tag Value: "+val.item(i).getNodeValue());
}
System.out.println();
}
}
}

}

OutPut:

Root Node: note

Tag Name: to
Tag Value: Tove

Tag Name: from
Tag Value: Jani

Tag Name: heading
Tag Value: Reminder

Tag Name: body
Tag Value: Don't forget me this weekend!

Sunday, August 19, 2007

Parsing & Binding XML

XML has arrived. Configuration files, application file formats, even database access layers make use of XML-based documents.Here is an accessible introduction to the two most widely used APIs
Application XML:











XML Processing:

Three traditional techniques for processing XML files are:

* Using a programming language and the SAX API.
* Using a programming language and the DOM API.
* Using a transformation engine and a filter









Xerses:

The Xerces Java Parser 1.4.4 supports the XML 1.0 recommendation and contains advanced parser functionality, such as support for the W3C's XML Schema recommendation version 1.0, DOM Level 2 version 1.0, and SAX Version 2, in addition to supporting the industry-standard DOM Level 1 and SAX version 1 APIs and supports Xml-dtd validation. For
more Info http://xerces.apache.org/xerces-j/

DOM Vs SAX Parsing:

Dom create the dom tree by parsing the given xml where as SAX Creates the Event Structure as shown below














DOM Example:

// Create a Xerces DOM Parser
DOMParser parser = new DOMParser();
// Parse the Document and traverse the DOM
parser.parse(xmlFile);
Document document = parser.getDocument();
traverse (document);
// Traverse DOM Tree and print elements names
private void traverse (Node node) {
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE)
System.out.println (node.getNodeName());
NodeList children = node.getChildNodes();
if (children != null) {
for (int i=0; i< color="#005e00">getLength
(); i++)
traverse (children.item(i));
}
}


SAX Example:

public class BasicSAX extends org.xml.sax.helpers.DefaultHandler {
public BasicSAX (String xmlFile) {
//Create a Xerces SAX Parser
SAXParser parser = new SAXParser();
//Set Content Handler
parser.setContentHandler (this);
//Parse the Document
parser.parse(xmlFile)
}

// Start Element Event Handler
public void startElement (String uri, String local, String qName, Attributes atts) {
System.out.println (local);

}

JAXP:

The Java API for XML Processing (JAXP) supports processing of XML documents using DOM, SAX, and XSLT. JAXP enables applications to parse and transform XML documents independent of a particular XML processing implementation.












SAX with JAXP:

import java.xml.parsers.*
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.*
...
SAXParserFactory factory =SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
parser.parse("sample.xml", handler);
// can also parse InputStreams, Files, and
// SAX input sources.

DOM With JAXP:


import
java.xml.parsers.*
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*
...
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("sample.xml");
// can also parse InputStreams, Files, and
// SAX input sources.

XSLT with JAXP


import java.xml.transform.*;
import javax.xml.transform.TransformerFactory;
...
Transformer transformer;
TransformerFactory factory =TransformerFactory.newInstance();
// Create a transformer for a particular stylesheet.transformer = factory.newTransformer(new StreamSource(stylesheet));
// Transform the source xml to System.out.
transformer.transform(new StreamSource(sourceId),new StreamResult(System.out));


Friday, August 17, 2007

XML Validation with DTD in Java

One thing you may have heard about XML is that it lets the system developer define custom tags. With a nonvalidating parser, you certainly have that ability. You can make up any tag you want and, as long as you balance your open and close tags and don't overlap them in absurd ways, the nonvalidating SAX parser will parse the document without any problems. For example, a nonvalidating SAX parser would correctly parse and fire events for the document in below.

A Well formed meaningless Document










Why DTD?

Two people generally can't talk to one another unless they speak a mutually understood language. Likewise, two programs can't communicate via XML unless the programs agree on the XML language they use. A DTD defines a set of rules for the allowable tags and attributes in an XML document, and the order and cardinality of the tags. Programs using the DTD must still agree on what the tags mean (semantics again), but a DTD defines the words (or, the tags) and the grammatical rules for a particular XML dialect.
In this section, you will learn to va
lidate a xml file against a DTD (Document Type Definition) using the DOM APIs. A DTD defines the document structure with a list of legal elements and attributes.

Program Description:

Validating a XML file against a DTD needs a xml file and its DTD document. First of all construct a well-formed xml file along with a DTD file . This DTD file defines all elements to keep in the xml file. After creating these, we parse the xml file using the parse() method and generates a Document object tree. The setErrorHandler() method invokes an object of DoucmentBuilder. Enable the setValidating() method of the factory to "true". If we pass 'true' the parser will validate xml documents otherwise not. To validate xml file , pass the DTD file as setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "fileinfo.dtd") in the transformer object.

DTD For above xml:











Code :(To perform xml validation)

import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ValidateXML {
public static void main(String args[]) {
try{

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new org.xml.sax.ErrorHandler() {
//To handle Fatal Errors
public void fatalError(SAXParseException exception)throws SAXException {
System.out.println("Line: " +exception.getLineNumber() + "\nFatal Error: "+exception.getMessage());
}
//To handle Errors
public void error(SAXParseException e)throws SAXParseException {
System.out.println("Line: " +e.getLineNumber() + "\nError: "+e.getMessage());
}
//To Handle warnings
public void warning(SAXParseException err)throws SAXParseException{
System.out.println("Line: " +err.getLineNumber() + "\nWarning: "+err.getMessage());
}
});
Document xmlDocument = builder.parse(new FileInputStream("fileinfo.xml"));
DOMSource source = new DOMSource(xmlDocument);
StreamResult result = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "fileinfo.dtd");
transformer.transform(source, result);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Tuesday, August 14, 2007

Generating SAX Parsing Events by Traversing an XML Document

If you have developed a set of handlers for SAX events, it is possible to use these handlers on a source other than a file. This example demonstrates how to use the handlers on a DOM document.

By DOM Parser:

DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder()
Document doc = builder.parse(new File("inputFile.xml"));

//Prepare the DOM source

Source source = new DOMSource(doc);

//Set the systemId of the source. This call is not strictly necessary

URI uri = new File("inputFile.xml").toURI();
source.setSystemId(uri.toString());

// Create a handler to handle the SAX events

DefaultHandler handler = new MyHandler();

try {
// Prepare the result
SAXResult result = new SAXResult(handler);

// Create a transformer
Transformer xformer = TransformerFactory.newInstance().newTransformer();

// Traverse the DOM tree
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}

// DefaultHandler contain no-op implementations for all SAX events.
// This class should override methods to capture the events of interest.
class MyHandler extends DefaultHandler {
}

By SAX Parser:

SAXParser parser=SAXParserFactory.newInstance().newSAXParser();

//Prepare InputSource
InputSource inputSource=new InputSource(new FileInputStream("inputFile.xml"))

// Create a handler to handle the SAX events
DefaultHandler handler = new MyHandler();


try{

parser.parse(inputSource, handler);

} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
// DefaultHandler contain no-op implementations for all SAX events.
// This class should override methods to capture the events of interest.
class MyHandler extends DefaultHandler {
}