【问题标题】:Java Transformer outputs &lt; and &gt; instead of <>Java Transformer 输出 < 和 > 而不是 <>
【发布时间】:2013-06-21 06:48:49
【问题描述】:

我正在使用 Transformer 通过添加更多节点来编辑 Java 中的 XML 文件。旧的 XML 代码没有改变,但新的 XML 节点有 &amp;lt;&amp;gt; 而不是 并且位于同一行。如何获得 而不是 &amp;lt;&amp;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);

谢谢

【问题讨论】:

  • 你能展示一个小样本输入和一个小样本输出吗?
  • 上述代码中没有提到&lt;&gt;。你是如何注射它们的?
  • 给我们一个线索!给我们看一些尖括号...

标签: java xml java-io


【解决方案1】:

基于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】:

    尝试将InputStream 而非Writer 传递给StreamResult

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

    The Transformer documentation 也暗示了这一点。

    【讨论】:

      【解决方案3】:

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

      StringEscapeUtils.unescapeXml(resp.toString());
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 1970-01-01
        • 2020-12-22
        相关资源
        最近更新 更多