跳至主要内容

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...

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation ...

Learn Spring Expression Language

When reading the source code of some Spring based projects, we can see some code like following: @Value( "${env}" ) private int value ; and like following: @Autowired public void configure (MovieFinder movieFinder, @ Value ("#{ systemProperties[ 'user.region' ] } ") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL. What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL. Features The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document : ...