mu_sa
mu_sa

Reputation: 2725

Difference between Element::textContent and NodeList::item::getNodeValue

I am new to XML and have a XML file with root and child and sub child tags.For one of the child tag name "Phone" i have the following implementation in Java using the DOM API. My question is that the last two lines of the code print the same result. In one case i am retrieving the content by using Element and in the other case its been retrived by NodeList function getNodeValue.

NodeList phoneNodeList = document.getElementsByTagName("Phone");
Node firstPhoneNode = phoneNodeList.item(0);
System.out.println (phoneNodeList.getLength());
Element phoneNodeElement = (Element) firstPhoneNode;
NodeList phoneList = phoneNodeElement.getElementsByTagName("Type");
Element phoneTypeElement = (Element) phoneList.item(0);
NodeList phoneType = phoneTypeElement.getChildNodes();
System.out.println ("NodeName : " + phoneTypeElement.getNodeName());
System.out.println ("Text Content : " + phoneTypeElement.getTextContent());
System.out.println ("Phone : " + phoneType.item(0).getNodeValue()); 

The Phone tag implementation looks something like this in the XML

<Phone>
<Type>work</Type>
<Value>2222</Value>
</Phone>

<Phone>
</Phone>

<Phone>
</Phone>

<Phone>
<Type>mobile</Type>
<Value>1111</Value>
</Phone>

Upvotes: 1

Views: 2075

Answers (1)

artbristol
artbristol

Reputation: 32397

The text within the <Type> element is itself a Node, of type TEXT, with the value mobile. That's just how DOM works. This page explains a bit more: http://docs.oracle.com/javase/tutorial/jaxp/dom/when.html

Upvotes: 1

Related Questions