Advertisement
vangop

splitXML

Sep 13th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. package sort;
  2.  
  3. import org.w3c.dom.Document;
  4. import org.w3c.dom.Node;
  5. import org.w3c.dom.NodeList;
  6. import org.w3c.dom.ls.DOMImplementationLS;
  7. import org.w3c.dom.ls.LSOutput;
  8. import org.w3c.dom.ls.LSSerializer;
  9. import org.xml.sax.SAXException;
  10.  
  11. import javax.xml.parsers.DocumentBuilder;
  12. import javax.xml.parsers.DocumentBuilderFactory;
  13. import javax.xml.parsers.ParserConfigurationException;
  14. import javax.xml.xpath.*;
  15. import java.io.BufferedWriter;
  16. import java.io.File;
  17. import java.io.FileWriter;
  18. import java.io.IOException;
  19.  
  20.  
  21. public class SplitXML {
  22.  
  23.  
  24.     public static void printXmlDocument(Document document) throws IOException {
  25.         DOMImplementationLS domImplementationLS =
  26.                 (DOMImplementationLS) document.getImplementation();
  27.         LSSerializer lsSerializer =
  28.                 domImplementationLS.createLSSerializer();
  29.         BufferedWriter bw=new BufferedWriter(new FileWriter(File.createTempFile("abc",".xml",new File("/tmp/abc"))));
  30.         LSOutput lsOutput = domImplementationLS.createLSOutput();
  31.         lsOutput.setCharacterStream(bw);
  32.         lsSerializer.write(document, lsOutput);
  33.     }
  34.  
  35.     public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
  36.         DocumentBuilderFactory f=DocumentBuilderFactory.newInstance();
  37.         f.setNamespaceAware(true);
  38.         DocumentBuilder builder = f.newDocumentBuilder();
  39.         Document doc = builder.parse("/home/akm/test.xml");
  40.  
  41.         XPathFactory xf=XPathFactory.newInstance();
  42.         XPath xpath=xf.newXPath();
  43.         XPathExpression exp=xpath.compile("//agreement[current_status='1']");
  44.         NodeList res= (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
  45.  
  46.  
  47.         for(int i=0;i<res.getLength();i++){
  48.             doc=f.newDocumentBuilder().newDocument();
  49.             Node root = doc.importNode(res.item(i), true);
  50.             doc.appendChild(root);
  51.             printXmlDocument(doc);
  52.         }
  53.  
  54.  
  55.  
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement