Question

Have an Xml response stored in a string, i want to display it in a textarea in gsp page

String responseXml = ""<Cars>
                           <Car>benz</Car>
                           <Car>audi</Car>
                           <Car>bmw</Car>
                       </Cars>""

in gsp page

<g:textArea name="xml" value="${responseXml}"  rows="20" cols="100"/>

getting response in textarea as a single line of xml tags like this

<Cars><Car>benz</Car><Car>audi</Car><Car>bmw</Car></Cars>

but what i want is display xml tags in textarea like this

<Cars>
   <Car>benz</Car>
   <Car>audi</Car>
   <Car>bmw</Car>
</Cars>
Was it helpful?

Solution

I created a taglib for this since I had this problem in muitiple places:

 /**
 * Preserves line breaks and spaces of the supplied value when displaying as html.
 * @param value - The value to preserve linebreaks of.
 */
def preserveFormat ={ attrs, body ->
    def value = attrs.value
    out << value.encodeAsHTML().replace('\n', '<br/>\n').replace(' ','&nbsp;').replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;')
 }

/**
 * Displays xml content in a pretty formatted way and preserves formatting in html view.
 */
def displayXml={attrs, body ->
    def xml = attrs.xml
    assert xml
    def prettyXml = groovy.xml.XmlUtil.serialize(xml)
    out << preserveFormat(value:prettyXml)
}

I updated my reply with an additional taglib that also formats xml in a pretty way according to suggestion in comments below.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top