Search code examples
grailsxml-formatting

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>

?


Solution

  • 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>