Search code examples
htmlxmlspring-bootthymeleafpretty-print

How to write XML in HTML


I want to display the following XML on a page in my Web application using Google Code Prettify and Thymeleaf (w/ Spring Boot):

<?xml version="1.0"?>
<users>
    <user uid="user12" name="Matt" mail="user12@example.com"/>
</users>

So I wrote the following HTML:

<pre id="code" class="prettyprint lang-xml">
&lt;&#x3f;xml version&#x3d;&quot;1.0&quot;&#x3f;&gt;
&lt;users&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;user uid&#x3d;&quot;user12&quot; name&#x3d;&quot;Matt&quot; mail&#x3d;&quot;user12&#x40;example.com&quot;&#x2f;&gt;
&lt;&#x2f;users&gt;</pre>

This works fine but the HTML code is very dirty. Could anyone tell me a way to write more human-readable code?


Solution

  • Well, that's how HTML work, so you need those HTML entities. What you can do if you use Thymeleaf is to provide the XML content as a variable. Thymeleaf automatically escapes the content of those variables if you use attributes like th:text. For example:

    <pre id="code" class="prettyprint lang-xml" th:text="${users}">
    
    </pre>
    

    This means you'll have to define the users variable somewhere though. This can be done from a Spring controller. You could create an XML file and read it as a string to pass it to the model, for example:

    @GetMapping
    public ModelAndView getPage() throws IOException {
        Resource resource = new ClassPathResource("users.xml");
        return new ModelAndView("index", "users", FileUtils.readFileToString(resource.getFile(), Charset.defaultCharset()));
    }
    

    You could probably move the file reading code somewhere separate, because right now you would have some overhead since you will be reading the XML file everytime someone would request the page.