Serializing to XML using JAXP DOM API

I was writing some Java codes to process some XML data and encountered an annoying problem which took me a while to fix. I want to put this down here in my blog in case I forget.

I'm using JAXP API to parse my XML to DOM, I then need to extract a sub-element and serialize it back to XML as string. It is working fine when run as a standalone application, but when I used the code in a servlet deployed in Tomcat I got "Provider org.apache.xalan.processor.TransformerFactoryImpl not found" exception. Initially I thought that maybe I'm missing my xalan.jar but then after googling I find a suggestion to set the system property to use another TransformerFactory implementation:


System.setProperty("javax.xml.transform.TransformerFactory",
"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");

Oh if any people out there are wondering how to get rid of the XML declaration header:
when serializing to XML, just set the output property.


DOMSource domSource = new DOMSource(xmldom);
StreamResult streamResult = new StreamResult(System.out); // print xml to stdout
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
serializer.transform(domSource, streamResult);

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Melvin Koh

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today