Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / macro / xml / ForceWordIDsMacro.groovy @ 1000

History | View | Annotate | Download (1.7 kB)

1
// STANDARD DECLARATIONS
2
package org.txm.macro.xml
3

    
4
import org.kohsuke.args4j.*
5
import groovy.transform.Field
6
import org.txm.rcp.swt.widget.parameters.*
7
import org.txm.importer.StaxIdentityParser
8
import javax.xml.stream.XMLStreamException
9

    
10
@Field @Option(name="inputFile", usage="input XML file", widget="FileOpen", required=true, def="input.xml")
11
def inputFile
12

    
13
@Field @Option(name="outputFile", usage="output XML file", widget="FileSave", required=true, def="ouput.xml")
14
def outputFile
15

    
16
// Open the parameters input dialog box
17
if (!ParametersDialog.open(this)) return;
18

    
19
// END OF PARAMETERS
20

    
21
if (!(inputFile.exists() && inputFile.canRead())) { println "Error: cannot found $inputFile"; return false;}
22

    
23
outputFile.getParentFile().mkdirs()
24

    
25
// build text id
26
textid = inputFile.getName();
27
if (textid.indexOf(".xml") > 0) {
28
        textid = textid.substring(0, textid.indexOf(".xml"))
29
}
30

    
31
def parser = new StaxIdentityParser(inputFile) {
32
        
33
        int wordnumber = 1;
34
        
35
        protected void writeAttributes() throws XMLStreamException {
36
                if (localname == "w") { // a word
37
                        boolean idwritten = false;
38
                        for (int i = 0 ; i < parser.getAttributeCount() ; i++) {
39
                                if (parser.getAttributeLocalName(i) == "id") { // update & backup
40
                                        writeAttribute(parser.getAttributePrefix(i), parser.getAttributeLocalName(i), "w_"+textid+"_"+(wordnumber++)); // force id
41
                                        writeAttribute(parser.getAttributePrefix(i), "foreign-id", parser.getAttributeValue(i)); // backup
42
                                        idwritten = true;
43
                                } else {
44
                                        writeAttribute(parser.getAttributePrefix(i), parser.getAttributeLocalName(i), parser.getAttributeValue(i));
45
                                }
46
                        }
47
                        
48
                        if (!idwritten) { // create id
49
                                writeAttribute(null, "id", "w_"+textid+"_"+(wordnumber++));
50
                        }
51
                } else {
52
                        super.writeAttributes()
53
                }
54
        }
55
}
56

    
57
return parser.process(outputFile)