【问题标题】:How to write XML in HTML如何在 HTML 中编写 XML
【发布时间】:2017-12-04 06:27:29
【问题描述】:

我想使用 Google Code Prettify 和 Thymeleaf(带 Spring Boot)在我的 Web 应用程序的页面上显示以下 XML:

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

所以我写了以下 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>

这工作正常,但 HTML 代码很脏。谁能告诉我一种编写更易于阅读的代码的方法?

【问题讨论】:

    标签: html xml spring-boot thymeleaf pretty-print


    【解决方案1】:

    嗯,这就是 HTML 的工作原理,所以你需要那些 HTML 实体。如果您使用 Thymeleaf,您可以做的是将 XML 内容作为变量提供。如果您使用 th:text 之类的属性,Thymeleaf 会自动转义这些变量的内容。例如:

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

    这意味着您必须在某处定义users 变量。这可以通过 Spring 控制器完成。您可以创建一个 XML 文件并将其作为字符串读取以将其传递给模型,例如:

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

    您可能可以将文件读取代码移动到单独的位置,因为现在您将有一些开销,因为每次有人请求页面时您都将读取 XML 文件。

    【讨论】:

    • 谢谢!这就是我一直在寻找的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多