4
5

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.

getTextContent()とgetNodeValue()の違いについての検証

Last updated at Posted at 2016-05-15

XMLノードの要素内容を取得するために、getTextContent()getNodeValue()のどっちを使うか一回迷ってしまいましたので、今回その違いについて検証してみました。

検証

以下のXML文書の中に、ノードproductNameの要素内容「Apple」を取得する。

<?xml version="1.0" encoding="UTF-8" ?>
<product>
	<productID>00001</productID>
	<productName>Apple</productName>
</product>

以下のJavaソースを使ってXMLファイルを読み込み、productNameノードを取得する。


	public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {

		// XMLファイル
		File xmlFile = new File("./resources/XML_1.xml");
		String xml = FileUtils.readFileToString(xmlFile, "UTF-8");
		
		// XML内容の読み込み
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes()));

		// ノードリスト
		NodeList nodeList = doc.getElementsByTagName("productName");
		// productNameノード
		Node node = nodeList.item(0);

	}

カレントノードがproductNameの場合

		System.out.println("getTextContent()の結果:" + selfNode.getTextContent());
		System.out.println("getNodeValue()の結果:" + selfNode.getNodeValue());

実行結果:

getTextContent()の結果:Apple
getNodeValue()の結果:null

カレントノードがproductNameの子要素(テキストノード)の場合

		System.out.println("getTextContent()の結果:" + selfNode.getFirstChild().getTextContent());
		System.out.println("getNodeValue()の結果:" + selfNode.getFirstChild().getNodeValue());

実行結果:

getTextContent()の結果:Apple
getNodeValue()の結果:Apple

結論

getTextContent()はノードのテキスト内容を取得するための方法です。getNodeValue()は、当該テキスト内容をテキストノードとして扱う場合(例:node.getFirstChild())、そのテキスト内容を取得できます。
プレゼンテーション1.png

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?