java 如何使用 XMLSerializer 正确缩进 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3638283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:46:26  来源:igfitidea点击:

How to indent XML properly using XMLSerializer?

javaandroidxml-serializationindentation

提问by

I'm having a hard time trying to indent XML files using XMLSerializer.

我在尝试使用 .xml 缩进 XML 文件时遇到了困难XMLSerializer

I've tried

我试过了

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

I've tried to append \ninto FileWriterbut the output is the \n's and \t's at the beginning of the file and not in the right place. I've tried setProperywith the proper URI etc.

我试图附加\n到,FileWriter但输出是文件开头的\n's 和\t's 而不是在正确的位置。我已经尝试过setPropery使用正确的 URI 等。

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?

我错过了什么?

采纳答案by naikus

Have you tried using these two properties "in combination" on Serializer?

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

// 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");

回答by

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);worked now.

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

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!

我不知道是我之前放过serializer.startDocument(encoding, standalone)还是出现了与 .xml 创建无关的内容的错误!

Thanks guys!

多谢你们!

回答by JonWillis

This is a solution in Java, andriod does support transformer so this should work.

这是 Java 中的一个解决方案,andriod 确实支持转换器,所以这应该可以工作。

// import additional packages
import java.io.*;

// import DOM related classes
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

// write the output file
try {
  // create a transformer
  TransformerFactory transFactory = TransformerFactory.newInstance();
  Transformer        transformer  = transFactory.newTransformer();

  // set some options on the transformer
  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");

  // get a transformer and supporting classes
  StringWriter writer = new StringWriter();
  StreamResult result = new StreamResult(writer);
  DOMSource    source = new DOMSource(xmlDoc);

  // transform the xml document into a string
  transformer.transform(source, result);

  // open the output file
  FileWriter outputWriter = new FileWriter(outputFile);
  outputWriter.write(writer.toString());
  outputWriter.close();

} catch(javax.xml.transform.TransformerException e) {
  // do something with this error
}catch (java.io.IOException ex) {
  // do something with this error
}

回答by Andrew Taylor

I just wanted to make a note that Transformer.setOutputProperties(Properties)doesn't seems to work for me (1.6.0_26_b03), but Transformer.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.

我只是想做一个Transformer.setOutputProperties(Properties)似乎对我不起作用的笔记(1.6.0_26_b03),但Transformer.setOutputProperty(String,String)做得很好。
如果您有一个 Properties 对象,您可能必须迭代并单独设置输出属性才能使其工作。