
NoXml - Luciano Fiandesio
By: a guest on Nov 5th, 2011 | syntax:
Groovy | size: 1.50 KB | hits: 94 | expires: Never
class NoXml {
private String xml;
private String origXml;
private String xmlFilePath;
def open(String path) throws IOException {
xmlFilePath = path;
xml = new File(path).getText();
origXml = xml;
this;
}
def getXml() {
xml;
}
def insertAfter(String nodeName, String xmlSnippet) {
// <pippo>...</pippo>
int closingTagStart = xml.indexOf("</" + nodeName);
int closingTagEnd = xml.indexOf(">", closingTagStart);
//System.out.println(closingTagStart + " " + closingTagEnd);
StringBuffer sb = new StringBuffer(xml);
sb.insert(closingTagEnd + 1, "\n" + xmlSnippet);
xml = sb.toString();
return this;
}
def replace(String nodeName, String xmlSnippet, String insertNode = null) {
int openTagStart = xml.indexOf("<" + nodeName);
int closingTagStart = xml.indexOf("</" + nodeName);
int closingTagEnd = xml.indexOf(">", closingTagStart);
//println "::debug " + openTagStart + " " + closingTagStart + " " + closingTagEnd
if (openTagStart == -1 || closingTagStart == -1) {
if (insertNode !=null) {
insertAfter(insertNode, xmlSnippet)
} else {
throw new Exception ("node to replace not found")
}
} else {
StringBuffer sb = new StringBuffer(xml);
sb.replace(openTagStart, closingTagEnd + 1, xmlSnippet);
xml = sb.toString();
}
return this;
}
def save() {
new File(xmlFilePath).write(xml)
return this;
}
def save(String path) {
writeFile(new File(path), xml);
return this;
}
}