DOM と String の変換について

よく忘れるのでメモ。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class DomUtil {

  /**
   * String -> DOM
   */
  public static synchronized Document String2Dom(String source, String encoding) throws Exception {
    //InputSource inputSource = new InputSource(new StringReader(source));
    InputSource inputSource = new InputSource(new ByteArrayInputStream(source.getBytes(encoding)));
    Document doc;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);
    doc = factory.newDocumentBuilder().parse(inputSource);
    return doc;
  }


  /**
   * DOM -> String
   */
  public static synchronized String Dom2String(Document doc, OutputFormat outputFormat)
      throws IOException {

    StringWriter sw = null;
    try {
      sw = new StringWriter();
      XMLSerializer stringSerializer = new XMLSerializer(sw, outputFormat);
      stringSerializer.serialize(doc);
      sw.flush();
    } catch (IOException e) {
      throw e;
    } finally {
      if (sw != null) {
        try {
          sw.close();
        } catch (IOException e) {
          throw e;
        }
      }
    }
    return sw.toString();
  }
}