【发布时间】:2013-06-21 06:48:49
【问题描述】:
我正在使用 Transformer 通过添加更多节点来编辑 Java 中的 XML 文件。旧的 XML 代码没有改变,但新的 XML 节点有 < 和 > 而不是 并且位于同一行。如何获得 而不是 < 和 > 以及如何在新节点之后获得换行符。我已经阅读了几个类似的主题,但无法获得正确的格式。以下是代码的相关部分:
// 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);
谢谢
【问题讨论】:
-
你能展示一个小样本输入和一个小样本输出吗?
-
上述代码中没有提到
<或>。你是如何注射它们的? -
给我们一个线索!给我们看一些尖括号...