LoginSignup
2
2

More than 5 years have passed since last update.

[java]JAXPのDocument文字列出力

Last updated at Posted at 2016-01-05

JAXPのDOMオブジェクトを文字列出力したい場合

// ドキュメントビルダーファクトリを生成
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
// ドキュメントビルダーを生成
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// パースを実行してDocumentオブジェクトを取得
Document document = builder.parse(new BufferedInputStream(new FileInputStream("test.xml")));
// ルート要素になっている子ノードを取得
Element root = document.getDocumentElement();

// DOMオブジェクトを文字列として出力したい
System.out.println(document.toString());

これだとnullが出力されてしまいます。

// ドキュメントビルダーファクトリを生成
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
// ドキュメントビルダーを生成
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// パースを実行してDocumentオブジェクトを取得
Document document = builder.parse(new BufferedInputStream(new FileInputStream("test.xml")));
// ルート要素になっている子ノードを取得
Element root = document.getDocumentElement();

// DOMオブジェクトを文字列として出力
StringWriter stringWriter = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
String xml = stringWriter.toString();
System.out.println(xml);

文字列出力する場合はこのように記述します。

にしてもdocument.toString()で
DOMオブジェクトの中身が文字列出力されるよう実装されててもいい気がするんですがなぜ標準で実装されてないんでしょう

誰か理由がわかる方教えてください。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2