开发者

How to display content in xml format after xml parsing in grails?

I have a sample.xml which looks like this

开发者_运维技巧<?xml version="1.0" ?> <Employee> <Name>ABC</Name> <EmpId>100011</EmpId> <Occupation>Programmer</Occupation> <Company>XYZ</Company> </Employee> ` and the code to parse it is

def display = {
        def parser = new XmlParser()
        def doc = parser.parse("grails-app/conf/sample.xml")
        def map =  [data: doc]
        render (view:'/myxml',model:map) }

When I run this app I get the output as shown on myxml.gsp

Employee[attributes={}; value=[Name[attributes={}; value=[ABC]], EmpId[attributes={}; value=[100011]], Occupation[attributes={}; value=[Programmer]],Company[attributes={}; value=[XYZ]]]]

Is there any way I can get it in the format as shown

<Employee>
<Name>ABC</Name>
<EmpId><100011</EmpId>
<Occupation>Programmer</Occupation>
<Company>XYZ</Company>
</Employee>

?


jjczopek is correct that render doc as XML is a good approach. If you want more control over things, or if your response is really HTML that includes an XML section, then you could use code like this:

def display = {
    def doc = new XmlParser().parse("grails-app/conf/sample.xml")
    def writer = new StringWriter()
    def nodePrinter = new XmlNodePrinter(new PrintWriter(writer))
    nodePrinter.preserveWhitespace = true
    nodePrinter.print doc

    render view: '/myxml', model: [xmlstring: writer.toString()]
}

and then in myxml.gsp you could display the XML with

<pre>
${xmlstring.encodeAsHTML()}
</pre>


If you read this file as normal text file , it should work. I am not sure of XML formatting though.


Documentation has some exaples on rendering response as XML (http://grails.org/doc/latest/ref/Controllers/render.html). I never used it yet, but maybe something like:

import grails.converters.*

...

render doc as XML
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜