2

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

2 に答える 2

2

getElementById属性によってDOM要素を取得するためのidものです。代わりにこれを試してください:

this.widgetDoc.getElementById("legendNode").appendChild(myNode);

DOM ノードを取得する他の方法については、 および を参照しquerySelectorquerySelectorAllください。

于 2012-04-18T11:07:49.687 に答える