开发者

XML Dom processing

开发者 https://www.devze.com 2023-01-22 03:22 出处:网络
I want to modify xml file using dom ,but when I make node.getNodeValue(); it returns null !I don\'t know why? my xml file contains the following tags:

I want to modify xml file using dom ,but when I make node.getNodeValue(); it returns null !I don't know why? my xml file contains the following tags: [person] which contains child [name] which contains childs [firstname ,middleInitial ,lastName] childs

I want to update First name , middleInitial and last name using dom this is my java dom processing file:

    NodeLis开发者_开发问答t refPeopleList = doc.getElementsByTagName("person");

for (int i = 0; i < refPeopleList.getLength(); i++) { NodeList personList = refPeopleList.item(i).getChildNodes(); for (int personDetalisCnt = 0; personDetalisCnt < refPeopleList.getLength(); personDetalisCnt++) { { currentNode = personList.item(personDetalisCnt); String nodeName = currentNode.getNodeName(); System.out.println("node name is " + nodeName); if (nodeName.equals("name")) { System.out.println("indise name"); NodeList nameList = currentNode.getChildNodes(); for(int cnt=0;cnt<nameList.getLength();cnt++) { currentNode=nameList.item(cnt); if(currentNode.getNodeName().equals("firstName")) { System.out.println("MODIFID NAME :"+currentNode.getNodeValue()); //prints null System.out.println("indide fname"+" node name is "+currentNode.getNodeName()); //prints firstName String nodeValue="salma"; currentNode.setNodeValue(nodeValue); System.out.println("MODIFID NAME :"+currentNode.getNodeValue());//prints null } } } }


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).


Is it firstName or firstname (watch the case).

0

精彩评论

暂无评论...
验证码 换一张
取 消