import java.io.*; import java.util.*; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class TransformDOM4J { public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } is.close(); return bytes; } public static void main(String args[]) { test(true); test(true); test(true); test(true); test(true); test(true); test(true); test(true); test(true); test(true); } public static void test(boolean forReal) { Document doc; long start; long end; XPath xpath; int kk=10; Number number = new Integer(0); List nodeList = null; try { byte[] content = getBytesFromFile(new File("blog.xml")); ByteArrayInputStream bais = new ByteArrayInputStream(content); ByteArrayOutputStream baos = new ByteArrayOutputStream(content.length * 2); XMLWriter writer = new XMLWriter(baos); SAXReader reader = new SAXReader(); doc = reader.read(bais); bais.reset(); XPath xpath1 = doc.createXPath("count(//*)"); XPath xpath2 = doc.createXPath("//item"); XPath xpath3 = doc.createXPath("/blog/item"); XPath xpath4 = doc.createXPath("//text()"); XPath xpath5 = doc.createXPath("count(//item)"); XPath xpath6 = doc.createXPath("count(/blog/item)"); XPath xpath7 = doc.createXPath("/blog/item/body/p/a"); start = System.currentTimeMillis(); for (int ii = 0; ii < kk; ii++) { //parse doc = reader.read(bais); number = xpath1.numberValueOf(doc); nodeList = xpath2.selectNodes(doc); nodeList = xpath3.selectNodes(doc); nodeList = xpath4.selectNodes(doc); number = xpath5.numberValueOf(doc); number = xpath6.numberValueOf(doc); Node node = doc.selectSingleNode("/blog/item[@num='a781']"); node.detach(); nodeList = xpath7.selectNodes(doc); Iterator it = nodeList.iterator(); while (it.hasNext()) { node = (Node) it.next(); node.detach(); } bais.reset(); writer.write(doc); baos.reset(); } end = System.currentTimeMillis(); if (forReal) System.err.println("cycle average (ms): " + (end - start) / kk + " ms"); } catch (Exception ie) { ie.printStackTrace(); } } }