java - XML Dom 处理

标签 java xml dom

我想使用 dom 修改 xml 文件,但是当我制作 node.getNodeValue(); 时它返回 null!我不知道为什么?我的 xml 文件包含以下标签: [person] which contains child [name] which contains childs [firstname ,middleInitial ,lastName] childs

我想使用 dom 更新名字、中间名和姓氏 这是我的 java dom 处理文件:

    NodeList 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 } } } }

最佳答案

而不是打电话 getNodeValue()/setNodeValue()关于<firstName>元素节点,尝试获取firstName元素的文本节点子节点,然后调用 getNodeValue()/setNodeValue()就在上面。

尝试

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());
}

来自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.

类似地,在 Node interface 的 Java 文档中,靠近顶部的表格显示某个元素的 nodeValue 为 null。

这就是为什么在元素上使用 getNodeValue 将始终返回 null,以及为什么您需要使用 getFirstChild () 首先为了获取文本节点(假设没有其他子节点)。如果存在元素和文本子节点的混合,可以使用 getNodeType () 检查哪个 child 是哪个(文本是类型 3)。

关于java - XML Dom 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4018342/

相关文章:

java - 如何加载和解析 SVG 文档

java - 错误 s4s-att-不允许 : Attribute 'type' cannot appear in element 'element'

html - 如何将数据属性添加到 ExtJs 呈现的 html?

javascript - javascript对象和html dom之间的内存利用率

javascript - 唯一的元素 ID,即使元素没有

java swing,main方法中必要的调用

java - 使用 Google 应用引擎或 Lucene 通过关键字映射进行搜索

java - 从命令行运行 Java 3D 程序

java - 天气应用程序 (JSON) 数据未显示在 TextView 中

php - 不同服务器上相同数据的 SimpleXML 差异