Groovy web console

subscribe to the feed Subscribe
to this
site

XSLT Challenge

Published 1 month ago by Raffael Herrmann
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def ins = """<?xml version="1.0" encoding="UTF-8"?>
<Document>
	<Header>
  <DocID>0000000001</DocID>
  <DocDate>15-04-2020</DocDate>
	</Header>
	<Line>
  <LineNo>1</LineNo>
  <MatNo>AB0056</MatNo>
  <Price>100.00</Price>
	</Line>
	<Line>
  <LineNo>2</LineNo>
  <MatNo>CD0078</MatNo>
  <Price>20.00</Price>
	</Line>
</Document>"""

    groovy.util.Node.metaClass.getVal {
        return delegate.'**'.find{x -> it.contains(x.name()) }.text()
    }

    groovy.util.NodeList.metaClass.asString {
        StringWriter stringWriter = new StringWriter()
        XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(stringWriter))
        nodePrinter.print(delegate[0])
        return stringWriter.toString()
    }

    def xml = new XmlParser().parseText(ins)
    def output = "<input>"+xml.Header.asString()
    xml.findAll{["Line","Material"].contains(it.name())}.each{
	output += "<item><MatNo>${it.getVal(["MatNo"])}</MatNo><NetPrice>${it.getVal(["Price","Prc"])}</NetPrice></item>"
    }
    output += "</input>"

    print(output)