View Javadoc
1   /*
2    * This file is a part of the SchemaSpy project (http://schemaspy.sourceforge.net).
3    * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier
4    *
5    * SchemaSpy is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU Lesser General Public
7    * License as published by the Free Software Foundation; either
8    * version 2.1 of the License, or (at your option) any later version.
9    *
10   * SchemaSpy is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   * Lesser General Public License for more details.
14   *
15   * You should have received a copy of the GNU Lesser General Public
16   * License along with this library; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18   */
19  package net.sourceforge.schemaspy.util;
20  
21  import javax.xml.transform.OutputKeys;
22  import javax.xml.transform.Transformer;
23  import javax.xml.transform.TransformerException;
24  import javax.xml.transform.TransformerFactory;
25  import javax.xml.transform.dom.DOMSource;
26  import javax.xml.transform.stream.StreamResult;
27  import org.w3c.dom.Node;
28  
29  public class DOMUtil {
30      public static void printDOM(Node node, LineWriter out) throws TransformerException {
31          TransformerFactory factory = TransformerFactory.newInstance();
32          Transformer xformer;
33          boolean indentSpecified = false;
34  
35          // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
36          // for issues about transformations in Java 5.x
37          try {
38              // won't work pre-5.x
39              factory.setAttribute("indent-number", new Integer(3));
40              indentSpecified = true;
41          } catch (IllegalArgumentException factoryDoesntSupportIndentNumber) {
42          }
43  
44          xformer = factory.newTransformer();
45          xformer.setOutputProperty(OutputKeys.INDENT, "yes");
46          if (!indentSpecified)
47              xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
48  
49          xformer.transform(new DOMSource(node), new StreamResult(out));
50      }
51  
52      /**
53       * Append the specified key/value pair of attributes to the <code>Node</code>.
54       * @param node Node
55       * @param name String
56       * @param value String
57       */
58      public static void appendAttribute(Node node, String name, String value) {
59          Node attribute = node.getOwnerDocument().createAttribute(name);
60          attribute.setNodeValue(value);
61          node.getAttributes().setNamedItem(attribute);
62      }
63  }