2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaでDOMの一部をXMLで見たい

Last updated at Posted at 2015-10-15

JavaってDOMの一部をXMLでさっと見れないの?

  • 今までは偶然にも(?)DOMを操作して、選んだNodeを生XMLで見たいと思うことがありませんでした。
  • JavaScriptで言うところのinnerHTML的なものが...あれ??ないんだっけ?

で、作りました。

  • 便利なライブラリを探せば一発で出来るのがあるかもしれませんが、探すのが面倒なので最初から入ってるライブラリで作りました。

ソースコード


import java.io.ByteArrayOutputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Util {

	public Util() {
		// TODO Auto-generated constructor stub
	}

	public static String convertXMLSource(final Node node) throws Exception  {

		// 空のドキュメントを作る。
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		// Nodeをコピー(インポート)する。
		document.appendChild(document.importNode(node, true));
		// XMLDocumentからDOMSouceを作る。
		DOMSource source = new DOMSource(document);
		// 変換ツールを作る。
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		// 変換オプションを設定する。
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");// インデントつける
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");// インデントは空白4文字分
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");// 先頭の<xml~~は付けない
		// 変換用のバッファを作る
		StreamResult result = new StreamResult(new ByteArrayOutputStream());
		// DOMSourceを表示用のXMLに変換する。
		transformer.transform(source, result);
		// 文字列
		return result.getOutputStream().toString();

	}
}

  • String xml = Util.convertXMLSource(node); みたいに使います。

ツッコミ・コメント上等!

  • もっといい手があるよ!とか、ココちがくない?ということがあればコメントよろしくお願いします。
2
6
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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?