如何使用XMLSerializer正确缩进XML?

时间:2010-09-03 17:51:52

标签: java android xml-serialization indentation

我很难尝试使用XMLSerializer缩进XML文件。

我试过

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

我尝试将\n附加到FileWriter,但输出是文件开头的\n\t,而不是正确的地点。我已尝试使用正确的URI等setPropery

部分代码:

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');

我错过了什么?

4 个答案:

答案 0 :(得分:36)

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

我不知道我是否在serializer.startDocument(encoding, standalone)之前放置它,或者出现与.xml创建无关的错误!

谢谢你们!

答案 1 :(得分:3)

您是否尝试在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");

答案 2 :(得分:2)

这是一个Java解决方案,android确实支持变换器,所以这应该可行。

// 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
}

答案 3 :(得分:1)

我只是想说明Transformer.setOutputProperties(Properties)似乎不适合我(1.6.0_26_b03),但Transformer.setOutputProperty(String,String)完美无缺。 如果您有一个Properties对象,则可能必须迭代并单独设置输出属性才能生效。