0

基于 StackOverflow 上的几个示例,我有以下用于缩进 XML 的代码。我有一个源 xml 文件String。然而,输出没有缩进,但它也没有给出任何错误。在调试器中检查输出,并且不包含任何可能被错误呈现并因此被忽略的字符,如空格或制表符。

String input = "xmldata";
Source xmlInput = new StreamSource(new StringReader(input));

StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
return stringWriter.toString();

我也尝试设置indent-amount"2",但是应用程序会抱怨未知属性。可能这在Android中没有实现。

我在这里做错了吗?是否有其他选项可以从源 xml 字符串生成缩进的 xml 文件?

4

1 回答 1

0

你可以尝试这样的事情:

String input = "xmldata";
InputSource is = new InputSource(new StringReader(input));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(is);
System.out.println(prettyPrint(doc));

public static final String prettyPrint(Node xml) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
    StringWriter stringWriter = new StringWriter();
    StreamResult out = new StreamResult(stringWriter);

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.transform(new DOMSource(xml), out);
    return out.getWriter().toString();
}
于 2013-04-09T17:57:25.783 回答