Statistics
| Revision:

root / tmp / org.txm.core / src / groovy / org / txm / importer / SetNewXmlDocumentRoot.groovy @ 148

History | View | Annotate | Download (1.4 kB)

1
package org.txm.importer
2

    
3
import javax.xml.parsers.*
4
import javax.xml.transform.*
5
import javax.xml.xpath.*
6

    
7
import org.txm.importer.graal.PersonalNamespaceContext
8
import org.txm.utils.xml.DomUtils
9
import org.w3c.dom.Document
10
import org.w3c.dom.Element
11
import org.w3c.dom.Node
12

    
13
class SetNewXmlDocumentRoot {
14
        public static boolean process(File xmlfile, String xpath) {
15
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
16
                domFactory.setNamespaceAware(true); // never forget this!
17
                DocumentBuilder builder = domFactory.newDocumentBuilder();
18
                Document doc = builder.parse(xmlfile);
19
                Element root = doc.getDocumentElement();
20
                
21
                XPathFactory xpathfactory = XPathFactory.newInstance();
22
                def _xpath = xpathfactory.newXPath();
23
                _xpath.setNamespaceContext(new PersonalNamespaceContext());
24
                def expr = _xpath.compile(xpath);
25
                def nodes = expr.evaluate(doc, XPathConstants.NODESET);
26

    
27
                for(Node node : nodes) {
28

    
29
                        Document document = builder.newDocument();
30
                        document.setXmlVersion("1.0");
31
                        document.setXmlStandalone(true);
32
                        Node adopted = document.adoptNode(node)
33
                        document.appendChild(adopted)
34
                        return DomUtils.save(document, xmlfile);
35
                }
36
                return false;
37
        }
38
        
39
        //                File xmlfile = new File("/home/mdecorde/xml/txmrefman/TEI/refman.xml")
40
        //                File outfile = new File("/home/mdecorde/xml/txmrefman/TEI/refman-o.xml")
41
        //                String xpath = "//body"
42
        
43
}