跳至主要内容

Validate and Parse XML in Java

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.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi...

LevelDB Source Reading (4): Concurrent Access

In this thread, we come to the issue of concurrent access of LevelDB. As a database, it can be concurrently accessed by users. But, it wouldn’t be easy to provide high throughput under product load. What effort does LevelDB make to achieve this goal both in design and implementation? Goal of Design From this github issue , we can see LevelDB is designed for not allowing multi-process access. this (supporting multiple processes) doesn’t seem like a good feature for LevelDB to implement. They believe let multiple process running would be impossible to share memory/buffer/cache, which may affect the performance of LevelDB. In the case of multiple read-only readers without altering the code base, you could simply copy the file for each reader. Yes, it will be inefficient (though not on file systems that dedupe data), but then again, so would having multiple leveldb processes running as they wouldn’t be able to share their memory/buffer/etc. They achieve it by adding a l...

LevelDB Source Reading (3): Compaction

LevelDB Source Reading (3): Compaction In the last blog that analyzes read/write process of Leveldb, we can see writing only happens to log file and memory table, then it relies on the compaction process to move the new updates into persistent sorted table for future use. So the compaction is a crucial part for the design, and we will dive into it in this blog. Compaction LevelDB compacts its underlying storage data in the background to improve read performance. The upper sentence is cited from the document of Leveldb , and we will see how it is implemented via code review. Background compaction // db_impl.cc void DBImpl :: MaybeScheduleCompaction ( ) { // use background thread to run compaction env_ - > Schedule ( & DBImpl :: BGWork , this ) ; } Two main aspects // arrange background compaction when Get, Open, Write void DBImpl :: BackgroundCompaction ( ) { // compact memtable CompactMemTable ( ) ; // compact ...