XMLStreamWriter:缩进 [英] XMLStreamWriter: indentation

查看:126
本文介绍了XMLStreamWriter:缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否真的无法使用javax.xml.stream.XMLStreamWriter(Java SE 6)直接编写格式化的XML?这真是令人难以置信,因为其他XML API(如JAXB和一些DOM库)能够做到这一点。即使.NET XMLStreamWriter等效也可以使用这个AFAIK(如果我没记错的话,那个类是System.Xml.XmlTextWriter)。

is there really no way to directly write formatted XML using javax.xml.stream.XMLStreamWriter (Java SE 6)??? This is really unbelievable, as other XML APIs such as JAXB and some DOM libraries are able to do this. Even the .NET XMLStreamWriter equivalent is able to this AFAIK (if I remember correctly the class is System.Xml.XmlTextWriter).

这意味着我唯一的选择是重新分析XML以生成格式化输出??

This means the only option I have is to reparse the XML to generate formatted output??

例如:

            StringWriter sw = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(sw);
    writeXml(xmlStreamWriter);
    xmlStreamWriter.flush();
    xmlStreamWriter.close();

    TransformerFactory factory = TransformerFactory.newInstance();

    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter formattedStringWriter = new StringWriter();
    transformer.transform(new StreamSource(new StringReader(sw.toString())), new StreamResult(formattedStringWriter));
    System.out.println(formattedStringWriter);

此解决方案的问题是属性{http://xml.apache.org/xslt }缩进量。我没有找到任何关于它的文档,它似乎不能保证是可移植的。

The problem with this solution is the property "{http://xml.apache.org/xslt}indent-amount". I didn't find any documentation about it and it doesn't seem to be guaranteed to be portable.

那么我有什么其他选择,如果我想做的话这与标准的Java 6类?创建一个JAXB或DOM对象图只是为了漂亮打印?

So what other options do I have, if I want to do this with standard Java 6 classes? Create a JAXB or DOM object graph just for pretty printing??

推荐答案

您可以添加必要的代码来格式化您的文档 writeXml 方法。只需保持深度计数器(以指示嵌套水平)。然后在writeStartElement之前和writeEndElement之后使用深度索引插入缩进。

You could add the necessary code to format your document in your writeXml method. Simply maintain a depth counter (to indicate the levels of nesting). Then before you writeStartElement and after you writeEndElement use the depth index to insert an indent.

for(int x=0; x<depth; x++) {
    xmlStreamWriter.writeCharacters("    ");
}

这篇关于XMLStreamWriter:缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆