如何使用XMLSerializer正确缩进XML?

14 java android indentation xml-serialization

我正在努力尝试使用缩进XML文件XMLSerializer.

我试过了

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
                      true);
Run Code Online (Sandbox Code Playgroud)

我试图追加\nFileWriter,但输出是\n的,并\t在文件的开头,而不是在正确的地方的.我尝试过setPropery使用正确的URI等.

部分代码:

XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
parserFactory .setNamespaceAware(true);
XmlSerializer serializer = parserFactory .newSerializer();
File xmlFile = new File(PATH + ".xml");         
FileWriter writer = new FileWriter(xmlFile);            
serializer.setOutput(writer);
//serializer.setProperty(INDENT_URL, INDENT);
serializer.startDocument("UTF-8", null);
//serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
                        true);
serializer.startTag(null, "bla");
writer.append('\n');
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

小智 36

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 现在工作了.

我不知道我之前是否提出它serializer.startDocument(encoding, standalone)或者与.xml创建无关的内容有错误!

多谢你们!


nai*_*kus 3

您是否尝试过在序列化器上“组合”使用这两个属性?

// indentation as 3 spaces
serializer.setProperty(
   "http://xmlpull.org/v1/doc/properties.html#serializer-indentation", "   ");
// also set the line separator
serializer.setProperty(
   "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n");
Run Code Online (Sandbox Code Playgroud)

  • 是的。我这样做了,它给了我这个错误: java.lang.RuntimeException: Unsupported Property: at org.kxml2.io.KXmlSerializer.setProperty(KXmlSerializer.java:260).... (9认同)