Processing XML Documents Partially
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
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.traversal.NodeIterator;
import org.xml.sax.InputSource;
import com.sun.org.apache.xpath.internal.CachedXPathAPI;
public class MainClass {
public static void main(String[] args) throws Exception {
InputSource in = new InputSource(new FileInputStream("y.xml"));
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
Document doc = dfactory.newDocumentBuilder().parse(in);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
CachedXPathAPI path = new CachedXPathAPI();
NodeIterator nl = path.selectNodeIterator(doc, "\\abc\\");
Node n;
while ((n = nl.nextNode()) != null)
transformer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
}
}
Related examples in the same category