01: package com.xoetrope.service.xml;
02:
03: import java.io.IOException;
04: import java.io.StringWriter;
05: import java.io.Writer;
06: import javax.xml.parsers.DocumentBuilder;
07: import javax.xml.parsers.DocumentBuilderFactory;
08: import javax.xml.transform.TransformerFactory;
09: import org.apache.xml.serializer.OutputPropertiesFactory;
10: import org.apache.xml.serializer.Serializer;
11: import org.apache.xml.serializer.SerializerFactory;
12: import org.w3c.dom.Document;
13: import org.w3c.dom.Node;
14:
15: /**
16: *
17: * <p> Copyright (c) Xoetrope Ltd., 2001-2006, This software is licensed under
18: * the GNU Public License (GPL), please see license.txt for more details. If
19: * you make commercial use of this software you must purchase a commercial
20: * license from Xoetrope.</p>
21: * <p> $Revision: 1.3 $</p>
22: */
23: public class DocumentHelper {
24:
25: public static Document createDocument() {
26: TransformerFactory tFactory = TransformerFactory.newInstance();
27: DocumentBuilder dBuilder = getDocumentBuilder(tFactory);
28: Document doc = dBuilder.newDocument();
29: return doc;
30: }
31:
32: /**
33: * Retrieve a document builder
34: */
35: public static DocumentBuilder getDocumentBuilder(
36: TransformerFactory tFactory) {
37: try {
38: //Instantiate a DocumentBuilderFactory.
39: DocumentBuilderFactory dFactory = DocumentBuilderFactory
40: .newInstance();
41:
42: // And setNamespaceAware, which is required when parsing xsl files
43: dFactory.setNamespaceAware(true);
44:
45: //Use the DocumentBuilderFactory to create a DocumentBuilder.
46: return dFactory.newDocumentBuilder();
47:
48: } catch (Exception e) {
49: e.printStackTrace();
50: return null;
51: }
52: }
53:
54: public static void outputXML(Node nod, Writer w) {
55: try {
56: Serializer serializer = SerializerFactory
57: .getSerializer(OutputPropertiesFactory
58: .getDefaultMethodProperties("xml"));
59: serializer.setWriter(w);
60: serializer.asDOMSerializer().serialize(nod);
61: } catch (IOException ex) {
62: ex.printStackTrace();
63: }
64: }
65:
66: public static String outputXML(Node nod) {
67: StringWriter sw = new StringWriter();
68: outputXML(nod, sw);
69: return sw.toString();
70: }
71: }
|