格式化XML以使属性垂直对齐

时间:2016-07-11 17:35:13

标签: java xml transform

我想知道是否有任何方法可以格式化我生成的XML文档,以便属性垂直对齐?下面是我编写的转换方法的片段。

我正在以这种方式创建Element:

    Element element = document.createElement(elementName);
    element.setAttribute("name", nameAttribute);
    element.setAttribute("id", idAttribute);
    element.setAttribute("val", valAttribute);

然后将它们添加到文档中以备转换。

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer;

    try {
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(document);
        File file = new File(fileName);

        StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
    }

我能够让缩进工作,但我也想知道是否有任何方法可以填充属性,以便它们在彼此之下排列。

目前它看起来像:

<ref name="message" type="message.sender">
    <p id="1" name="BeginString" val="${BeginString}"/>
    <p id="36" name="Message" val="${Message}"/>
    <p id="42" name="Sender" val="${Sender}"/>
    <p id="73" name="SendingTime" val="${SendingTime}"/>
    <p id="1134" name="Target" val="${Target}"/>
</ref>

但是我希望它的格式是这样的。

<ref name="message" type="message.sender">
    <p id="1"     name="BeginString" val="${BeginString}"/>
    <p id="36"    name="Message"     val="${Message}"/>
    <p id="42"    name="Sender"      val="${Sender}"/>
    <p id="73"    name="SendingTime" val="${SendingTime}"/>
    <p id="1134"  name="Target"      val="${Target}"/>
</ref>

这样做的唯一理由是,在较长的文件中,它使内容更容易阅读,并且该程序也将被提供给更少的技术人员。

由于

2 个答案:

答案 0 :(得分:0)

TL; DR - 任何标准或图书馆都没有这样做。

XML旨在供程序使用,而非人类使用。因此,非重要空间正是非重要的,并且序列化器不需要或预期对它们做任何特殊处理,或提供任何选项来漂亮地打印它们。特别是在协调不同标签之间的属性间距方面。

理论上,你可以提供自己的序列化程序,但这需要做很多工作,你必须决定什么构成需要将属性对齐的相邻标记,当属性顺序不同时会发生什么,等等等等。你总是会遇到你不能完全处理的情况&#34;对&#34;。

简而言之,没有什么标准可以达到你想要的效果,编写代码就可以了。恕我直言,浪费时间。

答案 1 :(得分:0)

I have never seen such functionality in an XML library.

If your document has only the structure you show it would be relatively easy to serialize as you like creating a custom ContentHandler that prints the XML as you want. Just extend DefaultHandler and implement startElement and endElement to print the ref and p elements. Use a library to XML-escape the attribute values. Then parse the document with the XMLReader obtained by an XMLReaderFactory and configured with the custom ContentHandler to trigger the events and print the document. It will also be much much faster than TrAX.

I would not normally reccomend to do this but if it really helps in enabling non techie to do things and leave developers alone then go for it.

相关问题