This blog will introduce two main method in Java to parse xml and validate them.
DOM
DOM represent the document object model, which represents the xml file in tree like object. If you are familiar with js, you will be very familiar with this. In Java, the code looks different, but the core abstraction is still the same.
The following code parse xml file and get Document
object, then we can get the root element of the tree and analyze by ourselves.
private void parseXML(String filename) throws IOException {
DocumentBuilder db = getDocumentBuilder();
try {
Document doc = db.parse(new File(filename));
// then handle your document through
} catch (SAXException e) {// handle parse exception}
}
private static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
private DocumentBuilder getDocumentBuilder() throws UnsupportedEncodingException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true); // don't forget this line
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); // set schema language or it will complain it
dbf.setAttribute(JAXP_SCHEMA_SOURCE, new File("yourSchema.xsd"));
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
assert false;
}
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, ENCODING);
db.setErrorHandler(new XMLParseErrorHandler(new PrintWriter(errorWriter, true)));
return db;
}
JAXB
Above way works, but it has following drawbacks:
- bad abstraction: we can just get the root of tree element and analyze by ourselves
- complicated code: as we can see, the way to get a
DocumentBuilder
is not so easy and we have to set some mysterious constants to make it works.
JAXB, by contrast, is a more advanced method to validate and parse xml and following is some fixed Java code snippet to run JAXB parser:
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = sf.newSchema(new File("youSchema.xsd"));
spf.setSchema(schema);
JAXBContext jc = JAXBContext.newInstance(GlobalConfig.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
SAXSource source = new SAXSource(xmlReader, new InputSource(new FileInputStream(parserSource.getSource())));
unmarshaller.setEventHandler(new PrintInfoHandler());
return (GlobalConfig) unmarshaller.unmarshal(source);
} catch (SAXException | JAXBException | ParserConfigurationException e) {
// handle execption
}
It is simpler and shorter. But what we get is more than that. We almost need no extra code to analyze xml element (except sometimes we need XmlAdapter
).
As far as I could see, it works like ORM (object relation mapping), in which we map xml structure to Java object and JAXB will translate it. In detail, we can use xml to annotate Java object as @XmlType
and mark it field as @XmlAttribute
or @XmlElement
and we are almost done.
More details can be found here, and here.
Written with StackEdit.
评论
发表评论