初めてこのプログラムを実行するとXMLを作成する必要があります。まずファイルを作成し、Documentオブジェクトを作成してからElementオブジェクトに変換します。要素ノードオブジェクトは、XML解析後にテキストノードに変換されます
xmlDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xmlDoc +="<head>";
xmlDoc += "</head>";
Document xmlFile = XmlParser.parseXmlString(xmlDoc);
Element element = xmlFile.getDocumentElement();
私はすでにそのノードタイプのコードでこれを確認しているが、私は親ノードを作成するとき、それは私が要素オブジェクトにこのノードを添付してくれELEMENT_NODEの== 1を与えます。
Element newElement = xmlFile.createElement("parent");
newElement.setAttribute("id", i);
element.appendChild(newElement);
それはすでに親要素の子ではない場合、私はそれが子供でない場合は、まだ私は新しいNodeクラスを作成し、与える、私はこれをチェックし、親に子を配置しますそれはテキストコンテンツです。
Node newChild = xmlFile.createElement("child");
newChild.setTextContent(text);
newElement.appendChild(newChild);
次に、このファイルをトランスで保存します。
Transformer transformer = null;
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(xmlFile);
StreamResult console = new StreamResult(System.out);
try {
transformer.transform(source, new StreamResult(new FileOutputStream(file.getPath())));
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ここでプログラムを2回実行すると、このファイルから直接解析されます。作成されたXMLファイルは、現在のファイルが作成されていることを
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<head>
<parent id="1">
<child>text1</child>
<child>text2</child>
<child>text3</child>
</parent>
<parent id="2">
<child>text1</child>
<child>text2</child>
</parent>
</head>
以下の構造を有しており、ファイルが読み込み代わりにハードコードされた文字列の要素を作成するために解析されます。
xmlDoc = this.readFile(file, Charset.forName("UTF-8"));
Document xmlFile = XmlParser.parseXmlString(xmlDoc);
Element element = xmlFile.getDocumentElement();
...
String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
問題が== 3.次のオブジェクトをキャストすることができない親要素が要素としてキャストすることができない今であり、TEXT_NODE型の値を有します。
Element nextSib = (Element) element.getFirstChild();
アイデアは、今私は私がid属性を使用できるように要素の形でそれを取得する必要がある理由である各親ノードを経由することにより、親に関連した子を追加することができるということです。しかし、何らかの理由で親ノードがテキストノードに変換されているので、これを行うことはできません。
また、インデントなしでファイルをシリアル化します。 –