Guest User

Untitled

a guest
Mar 6th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.50 KB | None | 0 0
  1. class NoXml {
  2.    
  3.     private String xml;
  4.     private String origXml;
  5.     private String xmlFilePath;
  6.    
  7.     def open(String path) throws IOException {
  8.         xmlFilePath = path;
  9.         xml = new File(path).getText();
  10.         origXml = xml;
  11.         this;
  12.     }
  13.    
  14.     def getXml() {
  15.         xml;
  16.     }
  17.    
  18.     def insertAfter(String nodeName, String xmlSnippet) {
  19.         // <pippo>...</pippo>
  20.         int closingTagStart = xml.indexOf("</" + nodeName);
  21.         int closingTagEnd = xml.indexOf(">", closingTagStart);
  22.  
  23.         //System.out.println(closingTagStart + " " + closingTagEnd);
  24.         StringBuffer sb = new StringBuffer(xml);
  25.         sb.insert(closingTagEnd + 1, "\n" + xmlSnippet);
  26.         xml = sb.toString();
  27.         return this;
  28.     }
  29.    
  30.     def replace(String nodeName, String xmlSnippet, String insertNode = null) {
  31.        
  32.         int openTagStart = xml.indexOf("<" + nodeName);
  33.         int closingTagStart = xml.indexOf("</" + nodeName);
  34.         int closingTagEnd = xml.indexOf(">", closingTagStart);
  35.        
  36.         //println "::debug " + openTagStart + " " + closingTagStart + " " + closingTagEnd
  37.        
  38.         if (openTagStart == -1 || closingTagStart == -1) {
  39.             if (insertNode !=null) {
  40.                 insertAfter(insertNode, xmlSnippet)
  41.             } else {
  42.                 throw new Exception ("node to replace not found")
  43.             }
  44.         } else {
  45.             StringBuffer sb = new StringBuffer(xml);
  46.             sb.replace(openTagStart, closingTagEnd + 1, xmlSnippet);
  47.             xml = sb.toString();
  48.         }
  49.         return this;
  50.     }
  51.  
  52.        
  53.     def save() {
  54.         new File(xmlFilePath).write(xml)
  55.         return this;
  56.     }
  57.  
  58.     def save(String path) {
  59.         writeFile(new File(path), xml);
  60.         return this;
  61.     }
  62.    
  63. }
Add Comment
Please, Sign In to add comment