如何在Android上正确缩进XML?

时间:2013-04-09 15:27:04

标签: android xml indentation

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

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文件?

1 个答案:

答案 0 :(得分: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();
}