从xml DOM中删除节点,xmldom删除节点,package cn.o
分享于 点击 40367 次 点评:22
从xml DOM中删除节点,xmldom删除节点,package cn.o
package cn.outofmemory.snippets.core;import java.io.File;import java.io.FileInputStream;import java.io.StringWriter;import java.io.Writer;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class RemoveNodesFromDOMDocumentRecursively { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new FileInputStream(new File("in.xml"))); // remove all elements named 'item' removeRecursively(doc, Node.ELEMENT_NODE, "item"); // remove all comment nodes removeRecursively(doc, Node.COMMENT_NODE, null); // Normalize the DOM tree, puts all text nodes in the // full depth of the sub-tree underneath this node doc.normalize(); prettyPrint(doc); } public static void removeRecursively(Node node, short nodeType, String name) { if (node.getNodeType()==nodeType && (name == null || node.getNodeName().equals(name))) { node.getParentNode().removeChild(node); } else { // check the children recursively NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { removeRecursively(list.item(i), nodeType, name); } } } public static final void prettyPrint(Document xml) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); System.out.println(out.toString()); }}
Xml文档如下
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"> <channel> <title>Java Tutorials and Examples</title> <item> <title><![CDATA[Java Tutorials]]></title> <link>http://www.javacodegeeks.com/</link> </item> <item> <title><![CDATA[Java Examples]]></title> <link>http://examples.javacodegeeks.com/</link> </item> </channel></rss>
输出:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss version="2.0"> <channel> <title>Java Tutorials and Examples</title> </channel></rss>
用户点评