我想知道是否很容易做到這一點與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的評價作爲潛在replacement to dom4j的一部分。)
目前您解析XML爲數據結構以任何特定的方式(JDOM等)?還是你從頭開始? –
示例XML中的輸入錯誤:structure1未正確關閉 – Jonik