这就像删除空目录:你必须做一个深度优先递归步行:如果所有子目录被删除,那么可以考虑删除当前目录。
因此,删除最好在Java中用递归完成。好处是,那个不需要副本。
代码
根据要求,与XML API的工作是相当零碎,一些未经测试的代码:
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XmlCleanup {
public static void main(String[] args) {
if (args.length == 0) {
args = new String[] { "/home/joop/Labortablo/test1.xml" };
}
new XmlCleanup().process(args[0]);
}
public void process(String xmlPath) {
try {
// Read XML document:
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new File(xmlPath));
removeEmptyChildElements(doc.getDocumentElement());
// Write XML document back:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(xmlPath
.replaceFirst("\\.xml$", "") + "-clean.xml"));
transformer.transform(source, result);
} catch (TransformerException ex) {
Logger.getLogger(XmlCleanup.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(XmlCleanup.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(XmlCleanup.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(XmlCleanup.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void removeEmptyChildElements(Element parentElement) {
List<Element> toRemove = new LinkedList<Element>();
NodeList children = parentElement.getChildNodes();
int childrenCount = children.getLength();
for (int i = 0; i < childrenCount; ++i) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) child;
removeEmptyChildElements(childElement);
if (elementIsRedundant(childElement)) {
toRemove.add(childElement);
}
}
}
for (Element childElement: toRemove) {
parentElement.removeChild(childElement);
}
parentElement.normalize();
}
private boolean elementIsRedundant(Element element) {
if (element.hasAttributes())
return false;
if (!element.hasChildNodes())
return true;
NodeList children = element.getChildNodes();
int childrenCount = children.getLength();
for (int i = 0; i < childrenCount; ++i) {
Node child = children.item(i);
String value = child.getNodeValue();
if (value != null && !value.matches("\\s*")) {
return false; // Found non-whitespace text
}
}
return true;
}
}
它采用java.xml.transform
所以你可以使用XSLT转换太;更简单一点就是使用javax.xml.stream.XMLOutputFactory
。
解析xml并验证子元素和属性的每个元素不是您的选项吗? – tartak 2012-02-01 14:33:32
@CatalinCiobanu是的,它可能是 – achraf 2012-02-01 14:47:25
以及你可以得到列表中的元素列表并要求大小......但我们的同胞Joop Eggen建议更好的(更好的)解决方案 - >递归! –
tartak
2012-02-01 14:54:27