我已经编写了一个 Web 服务(用 Java),它会生成一个(相当复杂的)XML 文档。
如果需要,我需要返回文档的 HTML 呈现。不必很花哨,用一些基本格式(例如正确缩进元素)显示 XML 源就可以了。
我该怎么做?
最佳答案
我同意,XSL 将是最好的方法。如果您想将其转换为实际上看起来像 XML 的内容,但只是在 HTML 中,您可以使用如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Evaluate Attributes -->
<xsl:template match="@*">
<span class="attribute">
<span class="name">
<xsl:value-of select="name()"/>
</span>="<span class="value"><xsl:value-of select="." /></span>"
</span>
</xsl:template>
<!-- Evaluate Elements -->
<xsl:template match="*" priority="10">
<div class="element">
<!-- First, create the opening tag with the attributes -->
<<span class="name"><xsl:value-of select="name()"/></span><xsl:apply-templates select="@*"/>>
<!-- Then, add children -->
<xsl:apply-templates select="node()"/>
<!-- Finally, add the closing tag -->
</<span class="name"><xsl:value-of select="name()"/></span>>
</div>
</xsl:template>
<!-- Just copy everything else (text, comments, etc.) -->
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
并添加一些 CSS:
.element{margin-left:4em;font-size:14px;}
.element .name{color:blue;}
.attribute{margin-left:8px}
更新:
<!-- Root node -->
<xsl:template match="/">
<div class="element">
<<span class="name"><xsl:value-of select="name()"/></span><xsl:apply-templates select="@*"/>
<!-- Grab all namespaces and declare them. distinct-values() is XPath 2.0, however. -->
<xsl:for-each select="distinct-values(//namespace::*)">
xmlns:<xsl:value-of select="name()" />="<xsl:value-of select="." />"
</xsl:for-each>
>
<xsl:apply-templates select="node()"/>
</<span class="name"><xsl:value-of select="name()"/></span>>
</div>
</xsl:template>
关于java - 将通用 XML 呈现为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154171/