Tuesday, March 29, 2011

XML Filter and Printer

def filename = "C:\\test.xml" // will create a file on your system here!

def example="""
<contacts>
   <campuscontact>
      <firstname>Jane</firstname>
      <lastname>Doe</lastname>
      <storenumber>123</storenumber>
   </campuscontact>
   <campuscontact>
      <firstname>Mike</firstname>
      <lastname>Jones</lastname>
      <storenumber>789</storenumber>
   </campuscontact>
   <campuscontact>
      <firstname>Joe</firstname>
      <lastname>Smith</lastname>
      <storenumber>555</storenumber>
   </campuscontact>
</contacts>"""

def nodes = new XmlParser().parseText(example)
def filterBy = ['555','123']

inList = nodes.CampusContact.grep {it.StoreNumber.text() in filterBy}
notInList = nodes.CampusContact.grep {!(it.StoreNumber.text() in filterBy)}
assert inList.size() == 2
assert notInList.size() == 1

//or

notInList = nodes.CampusContact.grep {!(it in inList)}
assert notInList.size() == 1

new PrintWriter(filename).with {
    append("<root>\n")
    p = new XmlNodePrinter(delegate)
    p.preserveWhitespace = true
    p.namespaceAware = false
    inList.each { p.print(it) }
    append("</root>").close()
}

/*
<root>
<campuscontact>
  <firstname>Jane</firstname>
  <lastname>Doe</lastname>
  <storenumber>123</storenumber>
</campuscontact>
<campuscontact>
  <firstname>Joe</firstname>
  <lastname>Smith</lastname>
  <storenumber>555</storenumber>
</campuscontact>
</root>
*/

http://groovyconsole.appspot.com/script/447002

No comments:

Post a Comment