如何使用 XMLSerializer 正确缩进 XML?
我在尝试使用 XMLSerializer
缩进 XML 文件时遇到了困难。
我尝试
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
true);
过将 \n
附加到 FileWriter
中,但输出是 \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');
我缺少什么?
I'm having a hard time trying to indent XML files using XMLSerializer
.
I've tried
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
true);
I've tried to append \n
into FileWriter
but the output is the \n
's and \t
's at the beginning of the file and not in the right place. I've tried setPropery
with the proper URI etc.
Part of the code:
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');
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
serializer.setFeature("http://xmlpull.org/v1/doc /features.html#indent-output", true);
现在可以工作了。我不知道我是否将其放在
serializer.startDocument(encoding,standalone)
之前,或者与 .xml 创建无关的内容出现错误!谢谢你们!
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
worked now.I dont know if i was putting it before
serializer.startDocument(encoding, standalone)
or there was a error with stuff not related to the .xml creation!Thanks guys!
您是否尝试过在序列化器上“组合”使用这两个属性?
Have you tried using these two properties "in combination" on Serializer?
这是Java中的一个解决方案,andriod确实支持变压器,所以这应该可以工作。
This is a solution in Java, andriod does support transformer so this should work.
我只是想指出
Transformer.setOutputProperties(Properties)
似乎对我不起作用 (1.6.0_26_b03),但Transformer.setOutputProperty(String,String)
> 表现完美。如果您有一个 Properties 对象,您可能必须迭代并单独设置输出属性才能使其正常工作。
I just wanted to make a note that
Transformer.setOutputProperties(Properties)
doesn't seems to work for me (1.6.0_26_b03), butTransformer.setOutputProperty(String,String)
does perfectly.If you have a Properties object, you might have to iterate and individually set the output property for it to work.