是否有任何 java xml 库可以按定义的顺序创建具有属性的 xml 标签? 我必须创建每个标签有 5 到 20 个属性的大型 xml 文件,并且我希望对属性进行排序以提高可读性。总是创建的属性应该在开头,其次是常用属性和很少使用的属性应该在最后。
最佳答案
这是一种基于 jdom 创建自定义输出器的简单方法:
JDOM 使用 XmlOutputter
将 DOM 转换为文本输出。属性打印方法:
protected void printAttributes(Writer out, List attributes, Element parent,
NamespaceStack namespaces) throws IOException
如您所见,属性通过一个简单的列表传递。 (简单的)想法是将此输出器子类化并覆盖该方法:
@Override
protected void printAttributes(Writer out, List attributes, Element parent,
NamespaceStack namespaces) throws IOException {
Collections.sort(attributes, new ByNameCompartor());
super.printAttributes(out, attribute, parent, namespaces);
}
比较器的实现应该没有那么困难。
关于保持属性有序的 Java XML 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7526062/