7

我正在使用 Transformer 通过添加更多节点来编辑 Java 中的 XML 文件。旧的 XML 代码没有改变,但新的 XML 节点使用&lt;and&gt;而不是 <> 并且位于同一行。如何获得 <> 而不是&lt;以及&gt;如何在新节点之后获得换行符。我已经阅读了几个类似的主题,但无法获得正确的格式。这是代码的相关部分:

// 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);

谢谢

4

3 回答 3

7

要替换 > 和其他标签,您可以使用 org.apache.commons.lang3:

StringEscapeUtils.unescapeXml(resp.toString());

之后,您可以使用转换器的以下属性在 xml 中换行:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
于 2014-02-11T12:57:57.323 回答
5

基于此处发布的问题:

public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.transform(docSource, new StreamResult(out));
}

产生:

<?xml version="1.0" encoding="UTF-8"?>

我看到的差异:

fDoc.setXmlStandalone(true);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
于 2013-06-24T17:06:35.560 回答
1

尝试通过InputStream而不是Writerto StreamResult

StreamResult result = new StreamResult(new FileInputStream(xmlFile.getAbsoluteFile()));

Transformer文档也表明了这一点。

于 2013-06-24T17:12:49.493 回答