Java DOM 通过 ID 获取元素

标签 java xml dom xml-parsing domparser

我正在使用 Java 中的 DOM 解析器将子节点添加到现有节点中。

我的 XML 是

<?xml version="1.0" encoding="iso-8859-1"?>
 <chart> 
<chart renderTo="pieContainer" defaultSeriesType="pie" zoomType="xy" plotBackgroundColor="null" plotBorderWidth="null"  plotShadow="false"></chart>
<legend id="legendNode">
  <align>center</align>
  <backgroundColor>null</backgroundColor>
  <borderColor>#909090</borderColor> 
  <borderRadius>25</borderRadius>
</legend>
 </chart>

有没有办法直接在现有节点下添加子节点?我可以使用这样的东西吗?

Node myNode = nodesTheme.item(0);
this.widgetDoc.getElementById("/chart/legend").appendChild(myNode);

我的代码

import org.w3c.dom.*;
import javax.xml.parsers.*;
public class TestGetElementById {
    public static void main(String[] args) throws Exception {

        String widgetXMLFile = "piechart.xml";
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

        domFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(widgetXMLFile);
        Node n = doc.getElementById("/chart/legend");
        //Node n = doc.getElementById("legendTag");

        Element newNode = doc.createElement("root");
        n.appendChild(newNode);
    }
}

最佳答案

编辑:对于原来的问题:是的,appendChild 事情按照您计划的方式工作,问题出在 getElementById 中。

NullPointerException 表示不存在具有该 ID 的元素。 javadoc 给出了它:

http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html#getElementById(java.lang.String)

The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID.

Attr 文档中的进一步内容:

http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Attr.html#isId()

所以基本上您需要文档的 DTD 或架构,并且需要设置

DocumentBuilderFactory.setValidating(true)

或手动设置 IsId 属性。

我个人使用:(为了懒惰而使用dirty&scala)

import org.w3c.dom.{Document,Node,Attr,Element}

def idify ( n:Node ) {
  if ( n.getNodeType() == Node.ELEMENT_NODE ){
        val e = n.asInstanceOf[Element ]
        if (e.hasAttributeNS(null , "id" ) )e.setIdAttributeNS(null , "id" , true )
  }
  val ndlist = n.getChildNodes()
  for ( i <- 0 until ndlist.getLength ) idify(ndlist.item(i) )
}

肯定有更专业的方法可以做到这一点,而无需起草完整的 DTD/架构。如果有人知道,我也很好奇。

关于Java DOM 通过 ID 获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10207774/

相关文章:

java - 配置 Hazelcast java 客户端以使用用户定义服务需要什么?

javascript - 如何递归删除多个子节点而不弄乱索引?

javascript - 如何在 NodeJS 中按值获取元素的 CSS 选择器?

javascript - 使用 TreeWalker 检索非 Javascript 文本节点

java - 如何通过api进行两次独立的修改

java - 如何获取用户输入的 double 值,然后用它执行计算

java - java中如何返回一张表的数据的数组列表?

java - 第 29 行中的标识符预期错误

java - 将 XML 输出生成为合适的格式以匹配我的 XSLT

python - 使用python修改xml值文件