Statistics
| Revision:

root / tmp / org.txm.core / src / java / org / txm / scripts / importer / SetNewXmlDocumentRoot.groovy @ 2473

History | View | Annotate | Download (1.5 kB)

1 1000 mdecorde
package org.txm.scripts.importer
2 881 mdecorde
3 881 mdecorde
import java.io.File;
4 881 mdecorde
5 881 mdecorde
import org.w3c.dom.Document;
6 881 mdecorde
import java.io.File;
7 881 mdecorde
8 881 mdecorde
import org.w3c.dom.Document;
9 881 mdecorde
import org.w3c.dom.Element;
10 881 mdecorde
import org.w3c.dom.Node;
11 881 mdecorde
12 881 mdecorde
import javax.xml.parsers.*;
13 881 mdecorde
import javax.xml.xpath.*;
14 881 mdecorde
import javax.xml.transform.*;
15 881 mdecorde
import javax.xml.transform.dom.DOMSource;
16 881 mdecorde
import javax.xml.transform.stream.StreamResult;
17 881 mdecorde
import org.txm.importer.PersonalNamespaceContext;
18 881 mdecorde
19 881 mdecorde
class SetNewXmlDocumentRoot {
20 881 mdecorde
        public static boolean process(File xmlfile, String xpath) {
21 881 mdecorde
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
22 881 mdecorde
                domFactory.setNamespaceAware(true); // never forget this!
23 881 mdecorde
                domFactory.setXIncludeAware(true);
24 881 mdecorde
                DocumentBuilder builder = domFactory.newDocumentBuilder();
25 881 mdecorde
26 881 mdecorde
                Document doc = builder.parse(xmlfile);
27 881 mdecorde
                Element root = doc.getDocumentElement();
28 881 mdecorde
29 881 mdecorde
                XPathFactory xpathfactory = XPathFactory.newInstance();
30 881 mdecorde
                def _xpath = xpathfactory.newXPath();
31 881 mdecorde
                _xpath.setNamespaceContext(new PersonalNamespaceContext());
32 881 mdecorde
                def expr = _xpath.compile(xpath);
33 881 mdecorde
                def nodes = expr.evaluate(doc, XPathConstants.NODESET);
34 881 mdecorde
35 881 mdecorde
                for(Node node : nodes) {
36 881 mdecorde
37 881 mdecorde
                        Document document = builder.newDocument();
38 881 mdecorde
                        document.setXmlVersion("1.0");
39 881 mdecorde
                        document.setXmlStandalone(true);
40 881 mdecorde
                        Node adopted = document.adoptNode(node)
41 881 mdecorde
                        document.appendChild(adopted)
42 881 mdecorde
                        return org.txm.utils.xml.DomUtils.save(document, xmlfile);
43 881 mdecorde
                }
44 881 mdecorde
                return false;
45 881 mdecorde
        }
46 881 mdecorde
47 881 mdecorde
        //                File xmlfile = new File("/home/mdecorde/xml/txmrefman/TEI/refman.xml")
48 881 mdecorde
        //                File outfile = new File("/home/mdecorde/xml/txmrefman/TEI/refman-o.xml")
49 881 mdecorde
        //                String xpath = "//body"
50 881 mdecorde
51 881 mdecorde
}