[groovy-user] XML without pretty printing

399 views
Skip to first unread message

AGood...@cfglife.com

unread,
Mar 30, 2012, 8:44:01 AM3/30/12
to Groovy User
Is there a Groovy way to get XML as a String that is not pretty printed? I could swear I have done so before. I ended up doing this, falling back on Java. It works, but...

    def dom = DOMBuilder.parse(...)
    ...
    TransformerFactory transformerFactory = TransformerFactory.newInstance()
    Transformer transformer = transformerFactory.newTransformer()
    StringWriter sw = new StringWriter()
    StreamResult sr = new StreamResult(sw)
    DOMSource source = new DOMSource(dom)
    transformer.transform(source, sr)
    String xmlString = sw.toString()

-Andy

Tim Yates

unread,
Mar 30, 2012, 9:22:29 AM3/30/12
to us...@groovy.codehaus.org
Not knowing what you're doing to modify the dom, here's an example that does some modification:

def prettyxml = '''<a>
                  |  <b>c</b>
                  |</a>'''.stripMargin()

dom = new XmlSlurper().parseText( prettyxml )
dom.appendNode {
  groovy( 'cool' )
}
String uglyxml = new groovy.xml.StreamingMarkupBuilder().bind {
  mkp.yield dom
}

assert uglyxml == '<a><b>c</b><groovy>cool</groovy></a>'

Tim

On 30 March 2012 14:10, <AGood...@cfglife.com> wrote:
The ellipsis I included in place of lines of code is where I modify the DOM. Then I need to get it back out as standard (unpretty) XML.

All of the doc wants it pretty and that seems to be straightforward - the default even. It seems like I should be able to get it out of the DOM without shenanigans.

I think I am missing something obvious.

> Not sure what you mean...  If you want to unprettify xml, you can do:

>
> def prettyxml = '''<a>

>                   |  <b>c</b>
>                   |</a>'''.stripMargin()
>
> String uglyxml = new groovy.xml.StreamingMarkupBuilder().bind {

>   mkp.yield new XmlSlurper().parseText( prettyxml )
> }
>
> Hope this helps!

>
> Tim

AGood...@cfglife.com

unread,
Mar 31, 2012, 8:31:35 AM3/31/12
to us...@groovy.codehaus.org
Thanks Paul.

I came to much the same conclusion - that there is not much there for the DOM classes in this regard.

It seems very strange and unGroovy that there is no simple way to get the XML out in its natural form. Apparently it is pretty or nothing!

It might be worth adding to the DOM doc (http://groovy.codehaus.org/Creating+XML+with+Groovy+and+DOM).(?)

-Andy

> If you were using XmlParser you could use XmlNodePrinter
> and if you were using XmlSlurper you could do as Tim suggests directly
> but because you are using the DOM classes you would need something like:
>
>      mkp.yield new XmlSlurper().parseText(XmlUtil.serialize(root))
>
> Which will do the round-tripping similar to what your Java version
> does but with only one line of code.
Reply all
Reply to author
Forward
0 new messages