An XML document can be given a formal specification. There are several methods
A DTD for login-requests is
This says that a
<!ELEMENT login-request (name, password)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT password (#PCDATA)>
login-request
must contain a
name
and a password
, and that their values
are implicitly strings (#PCDATA
).
A schema for login-requests is
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="loginrequest" type="LoginRequest"/>
<xsd:complexType name="LoginRequest">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="password" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
There are a number of ways of handling XML parsing in Java
We will use JAXB: a mechanism for
The JAXB compiler is xjc
and is found in the jaxb/bin
directory of Sun's Web services pack. It can be used by
xjc.sh -p package_dir login.xsd
It generates a bunch of classes including the interface
public interface LoginRequest {
java.lang.String getPassword();
void setPassword(java.lang.String value);
java.lang.String getName();
void setName(java.lang.String value);
}
It also generates an ObjectFactory which includes methods
public class ObjectFactory
extends impl.runtime.DefaultJAXBContextImpl
{
public ObjectFactory() {
// ...
}
public java.lang.Object newInstance(java.lang.Class javaContentInterface)
throws javax.xml.bind.JAXBException
{
// ...
}
public LoginRequest createLoginRequest()
throws javax.xml.bind.JAXBException
{
// ...
}
}
You need to use this factory to load the implementation of the interface -
you are not supposed to access the implementation classes directly.
A test program is
/**
* TestLoginRequest.java
*/
import java.io.*;
import javax.xml.bind.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import generated.LoginRequest;
public class TestLoginRequest{
public static void main(String[] args){
new TestLoginRequest();
}
public TestLoginRequest() {
InputStream in = null;
try {
in = new FileInputStream(new File("login.xml"));
} catch(java.io.FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
LoginRequest request = null;
try {
// tmp is the package name used in the -p option to xjc
JAXBContext jc = JAXBContext.newInstance("generated");
Unmarshaller u = jc.createUnmarshaller();
JAXBElement obj = (JAXBElement<LoginRequest>) u.unmarshal(in);
System.out.println("Type: " +obj.getClass().toString());
Object requestObj = obj.getValue();
request = (LoginRequest) requestObj;
System.out.println("TYpe: " + requestObj.getClass().toString());
} catch(JAXBException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Name is " + request.getName());
System.out.println("Password is " + request.getPassword());
System.exit(0);
}
} // TestLoginRequest