StAX XML format in Java

2022-09-01 18:21:47

是否可以使用StAX(特别是woodstox)使用换行符和选项卡格式化输出xml,即格式为:

<element1>
  <element2>
   someData
  </element2>
</element1>

而不是:

<element1><element2>someData</element2></element1>

如果这在woodstox中是不可能的,那么还有其他轻量级的库可以做到这一点吗?


答案 1

有 com.sun.xml.txw2.output.IncdentingXMLStreamWriter

XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));

答案 2

使用 JDK 变压器

public String transform(String xml) throws XMLStreamException, TransformerException
{
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Writer out = new StringWriter();
    t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
    return out.toString();
}

推荐