Skip to content

Commenting XML

Another mailing list question.

Not proud of this answer, but couldn’t come up with anything better…

Here’s the ‘commenting out’ part:

import groovy.xml.*
import groovy.xml.dom.DOMCategory

final CAR_RECORDS = '''
      <car name='HSV Maloo' make='Holden' year='2006'>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>

def reader = new StringReader(CAR_RECORDS)
def doc = DOMBuilder.parse(reader)
def records = doc.documentElement

use (DOMCategory) {

  def maloo = records.'car'[0]
  assert maloo.'@name' == 'HSV Maloo'

  maloo.replaceNode {
    'comment' XmlUtil.serialize(maloo)['<?xml version="1.0" encoding="UTF-8"?>'.size()..-1]

  println XmlUtil.serialize(records).replaceAll('<comment>', '<!--').replaceAll('</comment>', '-->')

This gives:

<?xml version="1.0" encoding="UTF-8"?><records>
      <!--&lt;car make="Holden" name="HSV Maloo" year="2006"&gt;&#13;
        &lt;record type="speed"&gt;Production Pickup Truck with speed of 271kph&lt;/record&gt;&#13;

This is SO yukky! If I really had to do this, I’d probably drop back to plain Java-style DOM manipulation (and even then it would STILL be very yukky).

(I gave up on the uncomment part…)

Tags: ,

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB