我使用JDom进行XML解析/格式化。 我希望将长行的属性分成几行。
喜欢:
<node att1="Foo" att2="Bar" att3="Foo" />
进入:
<node
att1="Foo"
att2="Bar"
att3="Foo" />
根据JDom FAQ,JDom可以转换为标准DOM和SAX事件。所以任何支持SAX或DOM并且能够进行这种漂亮渲染的渲染器都会很棒。
提前致谢。
答案 0 :(得分:5)
好的,我没有找到任何那样做的课程。 所以我自己实现了一个 org.jdom.output.XMLOutputter
的子类import java.io.IOException;
import java.io.Writer;
import java.util.*;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/** This outputter prints each attributes in a new line */
public class OneAttributePerLineOutputter extends XMLOutputter {
// ----------------------------------------------------
// Attribute
// ----------------------------------------------------
/** Limit wrapping attribute for one namespace */
String namespace = null;
/** Number of inline attributes before wrapping */
private int nbInlineAttribs;
// ----------------------------------------------------
// Constructor
// ----------------------------------------------------
/**
* @param namespace Limit wrapping attributes to one namespace. If null, all attributes are concerned
* @param nbInlineAttribs Allow a given number of inline elements before wrapping to several lines
*/
public OneAttributePerLineOutputter(
String namespace,
int nbInlineAttribs)
{
this.namespace = namespace;
this.nbInlineAttribs = nbInlineAttribs;
}
// ----------------------------------------------------
// Helpers
// ----------------------------------------------------
static private int elementDepth(Element element) {
int result = 0;
while(element != null) {
result++;
element = element.getParentElement();
}
return result;
}
// ----------------------------------------------------
// Overridden methods
// ----------------------------------------------------
@Override protected void printAttributes(
Writer writer,
List attribs,
Element parent,
NamespaceStack ns) throws IOException
{
// Loop on attributes
for (Object attribObj : attribs) {
Attribute attrib = (Attribute) attribObj;
// Check namespace
if ((this.namespace == null) ||
(this.namespace.equals(attrib.getNamespaceURI())))
{
// Reached max number of inline attribs ?
if (attribs.size() > this.nbInlineAttribs) {
// New line
writer.append("\n");
// Indent
for (int i=0; i < elementDepth(parent); i++) {
writer.append(this.getFormat().getIndent());
}
}
}
// Output single atribute
List list = new ArrayList<Object>();
list.add(attrib);
super.printAttributes(writer, list, parent, ns);
}
}
}
此序列化程序将遵循给定格式的缩进策略。
它允许仅将属性包装应用于单个命名空间(我需要该功能),并且可以在包装之前指定允许的最大内联属性数。
我希望这对某人有用。