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()
)、そのテキスト内容を取得できます。