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