Java Transformer输出<和>而不是<>

时间:2013-06-24 17:01:04

标签: java xml java-io

我正在使用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);

由于

3 个答案:

答案 0 :(得分:5)

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

StringEscapeUtils.unescapeXml(resp.toString());

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

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

答案 1 :(得分:4)

根据发布的问题here

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

答案 2 :(得分:1)

尝试将InputStream代替Writer传递给StreamResult

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

变形金刚documentation也暗示了这一点。

相关问题