【问题标题】:How to get properly indented XML on Android?如何在 Android 上正确缩进 XML?
【发布时间】:2013-04-10 01:57:25
【问题描述】:

基于 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 文件吗?

【问题讨论】:

    标签: android xml indentation


    【解决方案1】:

    你可以试试这样的:

    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();
    }
    

    【讨论】:

    • 我也试过了。它对我不起作用。我现在通过为 XML 节点编写自己的格式化程序解决了这个问题。
    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2011-02-04
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多