Statistics
| Revision:

root / tmp / org.txm.core / src / groovy / org / txm / scripts / FindUnclosedTag.groovy @ 187

History | View | Annotate | Download (1.6 kB)

1
package org.txm.scripts
2

    
3
import javax.xml.stream.XMLInputFactory;
4
import javax.xml.stream.XMLStreamConstants;
5

    
6
File xmlFile = new File("/home/mdecorde/xml/errorxml/error.xml")
7

    
8
def inputurl = xmlFile.toURI().toURL();
9
def inputData = inputurl.openStream();
10
def factory = XMLInputFactory.newInstance();
11
def parser = factory.createXMLStreamReader(inputData);
12

    
13
opened = []
14
locations = []
15
structPath = "/"
16

    
17
try {
18
for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
19
        switch (event) {
20
                case XMLStreamConstants.START_ELEMENT:
21
                String localname = parser.getLocalName();
22
                        startElement(localname, parser.getLocation().getLineNumber());
23
                break;
24
                case XMLStreamConstants.END_ELEMENT:
25
                        String localname = parser.getLocalName();
26
                        endElement(localname);
27
                break
28
        }
29
}
30
} catch(Exception e) {
31
        println "** Error while parsing: "+e
32
        println "** Error occured at : "+structPath+" line "+parser.getLocation().getLineNumber()
33
        println "** Opened tags: "+opened
34
        println "** at lines: "+locations
35
}
36

    
37
public boolean startElement(String localname, def loc) {
38
        println structPath
39
        structPath += localname+"/"
40
        opened << localname
41
        locations << loc
42
        return true;
43
}
44

    
45
public boolean endElement(String localname) {
46
        if (structPath.length() > 1) {
47
                def lastTag = opened[-1]
48
                if (localname != lastTag) {
49
                        println "ERROR: closing tag '$localname' does not match last opened tag '$lastTag'"
50
                        println opened
51
                        return false;
52
                }
53
        
54
                int idx = structPath.substring(0,structPath.length()-1).lastIndexOf("/");
55
                if (idx > 0)
56
                        structPath = structPath.substring(0, idx+1)
57
                //
58
                opened.pop()
59
                locations.pop()
60
                        
61
                return true
62
        }
63
}