2 回答
![?](http://img1.sycdn.imooc.com/545865470001bf9402200220-100-100.jpg)
TA贡献2016条经验 获得超9个赞
XMLWriter除非您想大量重写主要逻辑,否则您不能使用。但是,由于XMLWriter也是 SAX,ContentHandler它可以使用 SAX 事件并将它们序列化为 XML,并且在这种操作模式下,XMLWriter使用更易于定制的不同代码路径。下面的子类将给你几乎你想要的东西,除了空元素不会使用短格式<element/>。也许这可以通过进一步调整来解决。
static class ModifiedXmlWriter extends XMLWriter {
// indentLevel is private, need reflection to read it
Field il;
public ModifiedXmlWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException {
super(out, format);
try {
il = XMLWriter.class.getDeclaredField("indentLevel");
il.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
int getIndentLevel() {
try {
return il.getInt(this);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
protected void writeAttributes(Attributes attributes) throws IOException {
int l = getIndentLevel();
setIndentLevel(l+1);
super.writeAttributes(attributes);
setIndentLevel(l);
}
@Override
protected void writeAttribute(Attributes attributes, int index) throws IOException {
writePrintln();
indent();
super.writeAttribute(attributes, index);
}
}
public static void main(String[] args) throws Exception {
String XML = "<parameters>\n" +
" <parameter name=\"Tom\" city=\"York\" number=\"123\"/>\n" +
"</parameters>";
Document doc = DocumentHelper.parseText(XML);
XMLWriter writer = new ModifiedXmlWriter(System.out, OutputFormat.createPrettyPrint());
SAXWriter sw = new SAXWriter(writer);
sw.write(doc);
}
示例输出:
<?xml version="1.0" encoding="UTF-8"?>
<parameters>
<parameter
name="Tom"
city="York"
number="123"></parameter>
</parameters>
![?](http://img1.sycdn.imooc.com/5333a0350001692e02200220-100-100.jpg)
TA贡献1786条经验 获得超13个赞
一般来说,很少有 XML 序列化程序可以让您对输出格式进行这种级别的控制。
如果指定选项method=xml
, indent=yes
, ,则可以使用 Saxon 序列化程序获得与此类似的结果saxon:line-length=20
。Saxon 序列化器能够将 DOM4J 树作为输入。您将需要 Saxon-PE 或 -EE,因为它需要 Saxon 命名空间中的序列化参数。它仍然不是您想要的,因为第一个属性将与元素名称在同一行,而其他属性将在第一个属性下方垂直对齐。
添加回答
举报