小编典典
我想知道使用XOM库这样做是否容易,并尝试一下。
事实证明这很容易:
import nu.xom.*;
import java.io.File;
import java.io.IOException;
public class RemoveEmptyTags {
public static void main(String[] args) throws IOException, ParsingException {
Document document = new Builder().build(new File("original.xml"));
handleNode(document.getRootElement());
System.out.println(document.toXML()); // empty elements now removed
}
private static void handleNode(Node node) {
if (node.getChildCount() == 0 && "".equals(node.getValue())) {
node.getParent().removeChild(node);
return;
}
// recurse the children
for (int i = 0; i < node.getChildCount(); i++) {
handleNode(node.getChild(i));
}
}
}
这可能无法正确处理所有极端情况,例如完全空的文档。对于原本为空但具有属性的元素该怎么办?
如果要保存带有属性的XML标签,我们可以在方法’handleNode’中添加以下检查:
... && ((Element) node).getAttributeCount() == 0) )
另外,如果xml有两个或多个空标记,则一个接一个。此递归方法不会删除所有空标签!
(此答案是我对XOM作为dom4j的潜在替代品的评估的一部分。)
2020-10-16