//-- user.xml --
<?xml version="1.0" encoding="UTF-8"?>
<root
xmlns="http://solnone"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://solnone user.xsd">
<user>
<name>Solnone</name>
<birthday>1974-01-01</birthday>
</user>
</root>
//-- user.xsd --
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://solnone" xmlns="http://solnone"
elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="user">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="birthday" type="xs:date" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
//-- Main.java --
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
// Specify schema
// factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
// "file:./user.xsd");
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("user.xml"));
System.out.println("Encoding: " + doc.getXmlEncoding());
System.out.println("Root tag Name: " + doc.getDocumentElement().getTagName());
}
}
2009年1月5日
XML Validate with schema
W3C XML Schema
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言