I am using DOM parser in Java to add child nodes into existing nodes.
My XML is
center
null
#909090
25
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);
My Code
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 is specifically for retrieving DOM elements by their id attribute. Try this instead:
this.widgetDoc.getElementById("legendNode").appendChild(myNode);
For other ways of retrieving DOM nodes, look into querySelector and querySelectorAll.