Java DOM getElementByID [英] Java DOM getElementByID
本文介绍了Java DOM getElementByID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Java中的DOM解析器将子节点添加到现有节点中。
I am using DOM parser in Java to add child nodes into existing nodes.
我的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>
是否可以直接在现有节点下添加子节点?我可以使用这样的东西吗?
Is there any way to directly add child nodes under existing ones? Can I use something like this?
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);
}
}
推荐答案
getElementById
专门用于通过其 id
属性检索DOM元素。尝试以下操作:
getElementById
is specifically for retrieving DOM elements by their id
attribute. Try this instead:
this.widgetDoc.getElementById("legendNode").appendChild(myNode);
有关检索DOM节点的其他方法,请查看 querySelector
和 querySelectorAll
。
For other ways of retrieving DOM nodes, look into querySelector
and querySelectorAll
.
这篇关于Java DOM getElementByID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文