2 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
XMLWriter除非您想大量重寫主要邏輯,否則您不能使用。但是,由于XMLWriter也是 SAX,ContentHandler它可以使用 SAX 事件并將它們序列化為 XML,并且在這種操作模式下,XMLWriter使用更易于定制的不同代碼路徑。下面的子類將給你幾乎你想要的東西,除了空元素不會(huì)使用短格式<element/>。也許這可以通過進(jìn)一步調(diào)整來解決。
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>

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
一般來說,很少有 XML 序列化程序可以讓您對(duì)輸出格式進(jìn)行這種級(jí)別的控制。
如果指定選項(xiàng)method=xml
, indent=yes
, ,則可以使用 Saxon 序列化程序獲得與此類似的結(jié)果saxon:line-length=20
。Saxon 序列化器能夠?qū)?DOM4J 樹作為輸入。您將需要 Saxon-PE 或 -EE,因?yàn)樗枰?Saxon 命名空間中的序列化參數(shù)。它仍然不是您想要的,因?yàn)榈谝粋€(gè)屬性將與元素名稱在同一行,而其他屬性將在第一個(gè)屬性下方垂直對(duì)齊。
添加回答
舉報(bào)