Groovy:Xml: How to display Xml response in textarea of gsp page

孤街醉人 提交于 2019-12-24 05:57:56

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/23468389/groovyxml-how-to-display-xml-response-in-textarea-of-gsp-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!