从DOM中生成SAX Events:
//parse the XML file to a W3C DOM
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
dbfactory.setNamespaceAware(true);
DocumentBuilder domparser = dbfactory.newDocumentBuilder();
Document doc = domparser.parse(new File("data.xml"));
//prepare the DOM source
Source xmlsource = new DOMSource(doc);
//create a content handler to handle the SAX events
ContentHandler handler = new MyHandler();
//prepare a SAX result using the content handler
Result result = new SAXResult(handler);
//create a transformer factory
TransformerFactory xfactory = TransformerFactory.newInstance();
//create a transformer
Transformer xformer = xfactory.newTransformer();
//transform to raise the SAX events from DOM
xformer.transform(xmlsource, result);
上面的例子中,我们创建Transformer的时候没有用到XSL。这意味着这个转换器对XML不会有任何的转换,source和result是一样的。当你实际相要用XSL来转换,你应该创建一个使用了XSL的转换器,就像下面一样:
//create the xsl source
Source xslsource = new StreamSource(new File("mystyle.xsl"));
//create the transformer using the xsl source
Transformer xformer = xfactory.newTransformer(xslsource);
JAXP1.3有哪些新特性?
除了支持SAX解析,DOM解析,根据DTD/ XMLSchema的校验,使用XSL-T转换,和以前的版本相比JAXP1.3新支持的特性有:
1.XML 1.1 和XML 1.1名字空间
2.XML Inclusions - XInclude 1.0
3.根据预解析的schema来校验文档。
4.XPath表达式的计算.
5.以前XMLSchema 1.0, XPath 2.0 和XQuery 1.0中的某些数据类型不能被映射到java里的数据类型 ,现在可以了。
使用JAXP1.3
XML1.1主要支持的特性如下:
1.向前兼容不断增长的Unicode字符集。
2.在行结束(line-end)字符集中新添加了NEL (#x85)和Unicode行分隔符(#x2028)。
