ノードを追加して、Transformer を使用して Java で XML ファイルを編集しています。古い XML コードは変更されていませんが、新しい XML ノードには <> の代わりに and があり、同じ行にあります<
。and>
の代わりに <> を取得する方法と、新しいノードの後に改行を取得する方法を教えてください。私はすでにいくつかの同様のスレッドを読みましたが、正しいフォーマットを取得できませんでした. コードの関連部分は次のとおりです。<
>
// Read the XML file
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse(xmlFile.getAbsoluteFile());
Element root = doc.getDocumentElement();
// create a new node
Element newNode = doc.createElement("Item");
// add it to the root node
root.appendChild(newNode);
// create a new attribute
Attr attribute = doc.createAttribute("Name");
// assign the attribute a value
attribute.setValue("Test...");
// add the attribute to the new node
newNode.setAttributeNode(attribute);
// transform the XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
StreamResult result = new StreamResult(new FileWriter(xmlFile.getAbsoluteFile()));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
ありがとう