tags:

views:

26

answers:

2
+2  A: 

Rather than calling getNodeValue() / setNodeValue() on the <firstName> element node, try getting the firstName element's text node child, and call getNodeValue() / setNodeValue() on it.

Try

if(currentNode.getNodeName().equals("firstName"))
{
   Node textNode = currentNode.getFirstChild();
   System.out.println("Initial value:" + textNode.getNodeValue());
   String nodeValue="salma";
   textNode.setNodeValue(nodeValue);
   System.out.println("Modified value:" + textNode.getNodeValue());
}

From the DOM spec,

The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface. In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment), this returns null.

Similarly in the Java docs for the Node interface, the table near the top shows that the nodeValue of an element is null.

This is why using getNodeValue on an element will always return null, and why you need to use getFirstChild() first in order to get the text node (assuming there are no other child nodes). If there is a mixture of element and text child nodes, you can use getNodeType() to check which child is which (text is type 3).

LarsH
firstName element is simple data type , it doesn't have childs , how can i get element child?
Alaa
firstName element doesn't have child *elements*, but it does have a child *text node*. The text inside the firstName element is not on element itself, but is the value of the element's text node child.
LarsH
@Alaa, I edited my answer to give more details about child text nodes.
LarsH
i make like this , but still not working , i don't know where i am making the mistake! String nodeValue="alaa"; currentNode.getFirstChild().setNodeValue(nodeValue); by the way , ur answer hasn't been changed !!
Alaa
@Alaa, if you look at http://stackoverflow.com/posts/4018398/revisions you can see when my answer changed.
LarsH
@Alaa, when you do `currentNode.getFirstChild().getNodeValue()` what is the result?
LarsH
:) it works , many thanx mr @LarsH , thanx for being sooooo patient.
Alaa
@Alaa, Glad to help! :-)
LarsH
A: 

is it firstName or firstname (watch the case)

Ramp
it's firstName , it's just writing mistake
Alaa