Showing posts with label JAXP. Show all posts
Showing posts with label JAXP. Show all posts

1 December 2014

Setting the JAXP validation file (updated)

A JAXP parser validates (version >= 1.2) by default using a DTD. Here are some variations that can be used when validating

  • If you are using SAX and obtained this parser from the SAXParserFactory:
  • javax.xml.parsers.SAXParser parser
    • To validated using a schema (xsd) add this line of code to your parser setup:
    • parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
        XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    • To specify the schema file in your code (for both DTD and XSD) add this line to your parser setup:
    • parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", 
        new File("checkers.xsd")); 
                  SL-385.B: add to code 3-2 after line 17   
      • The source can be a File, InputStream, InputSource or an Object array containing these types
  • If you are using DOM, and you created this DocumentBuilderFactory instance :
  • javax.xml.parsers.DocumentBuilderFactory builder
    • To validated using a schema (xsd) add this line of code to your parser setup:
    • builder.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
        XMLConstants.W3C_XML_SCHEMA_NS_URI);
      • XMLConstants.W3C_XML_SCHEMA_NS_URI = http://www.w3.org/2001/XMLSchema
      • The corresponding constant for DTD (the default) in these cases is  
      • XMLConstants.XML_DTD_NS_URI = http://www.w3.org/TR/REC-xml
    • To specify the schema file in your code (for both DTD and XSD) add this line to your parser setup:
    • builder.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", 
        new File("checkers.xsd")); 

22 November 2014

JAXP history (updated)

Java SE JAXP What’s new
DOM level 0: javascript in NS/IE v3
1.0
DOM level 1 (tree), SAX 1.0 (push)
org.xml.sax.Parser
1.4
1.1
DOM Level 2, SAX 2.0 (+validation), TrAX (XSLT)
Apache Crimson XMLReader
1.2
XML Schema
Apache Xerces2 XMLReader
5
1.3
DOM level 3, XML 1.1, XInclude 1.0, Xpath 1, Validator API
6
1.4
StAX (pull)
SE also bundles JAXB
7u40
1.5
8
1.6
9
- no separate JAXP anymore, moved into Java SE

More details on DOM levels.

14 October 2010

Handling comments with SAX

DOM and StAX will readily handle XML comments.
With SAX 2 you will need to register an extra handler, LexicalHandler, to be called for comments and other lexical events (CDATA, DTD, Entities). The JAXP adapter class DefaultHandler2 is an adapter for all SAX2 handlers, including the LexicalHandler.
Here's a little code snippet, that shows how to set up your SAX parser to print comments:

      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      parser.setProperty(
        "http://xml.org/sax/properties/lexical-handler",
        new LexicalHandler() {
          public void comment(char[] ch, int start, int length)
            throws SAXException {
            System.out.println(
              "/* comment: " + String.valueOf(ch, start, length) + " */");
          }
          public void startDTD(String name, String publicId, String systemId)
            throws SAXException { }
          public void endDTD() throws SAXException { }
          public void startEntity(String name) throws SAXException { }
          public void endEntity(String name) throws SAXException { }
          public void startCDATA() throws SAXException { }
          public void endCDATA() throws SAXException { } 
        });

9 October 2010

Load and Save XML with DOM (Level 3)

Prior to DOM Level 3, DOM did not standardize reading and writing XML.
Below is the  SL-385 code 4-2 modified to use the standard DOM level 3 Load and Save (LS) API.
An alternative JAXP (but not DOM standard) way is to read using the JAXP DocumentBuilder and to write using the JAXP transformer (TrAX XSLT).
(I included a comment showing DOM LS writing starting from a DocumentBuilder obrained from JAXP reading as well.)


// SimpleDOML3LS.java
import org.w3c.dom.*;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.*;
import java.io.OutputStreamWriter;

public class SimpleDOML3LS {

  public static void main(String args[]) {
    Document doc;
    try {

      // Create DOM Document using DOM Level 3 Load 
      DOMImplementationLS ls = (DOMImplementationLS) DOMImplementationRegistry.
          newInstance().getDOMImplementation("LS");
      LSParser builder = ls.createLSParser(
        DOMImplementationLS.MODE_SYNCHRONOUS,
        null);
      doc = builder.parseURI(args[0]);

      // Obtain root elements
      Element root = doc.getDocumentElement();

      // Add comment texts
      Comment comment = doc.createComment("Training text");
      root.appendChild(comment);

      // Output to standard output; using DOM Level 3 save

      // If you parsed using a JAXP DocumentBuilder
      // you can also get your LSimplementation from your Document:
      // DOMImplementationLS ls = (DOMImplementationLS) doc.
      //   getImplementation().getFeature("LS","3.0");
      LSOutput target = ls.createLSOutput();
      target.setCharacterStream(new OutputStreamWriter(System.out));
      ls.createLSSerializer().write(doc, target);

    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
  }
}
To add newlines/indents to enhance readability of the output, replace in the above example
ls.createLSSerializer().write(doc, target);
with
      LSSerializer serializer = ls.createLSSerializer();
      DOMConfiguration serializerConfig = serializer.getDomConfig();
      serializerConfig.setParameter("format-pretty-print", Boolean.TRUE);
      serializer.write(doc, target);