如何使用xslt在html页面中显示一些xml节点?

时间:2013-04-01 21:56:51

标签: html xml xslt

我正在使用xslt在xml文件上应用一些模板并输出一个html页面。所以我将'xsl:output'的方法定义为'html'。但是,我需要以原始格式显示xml文件中的一些xml节点,不幸的是它们并没有像我预期的那样出现在html页面上。

这是示例xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>
    <employee>
        <name>Hello World</name>
        <title>UI Designer</title>
    </employee>
</employees>

我的xslt如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>

    <xsl:template match="/">
    <html>
    <head>
        <title>Example of Employee Data</title>
    </head>  
    <body>
        <h2>The following shows the structure of employee data file: </h2>
        <div style="background-color: grey">
            <xsl:copy-of select="employees/employee"/>
        </div>
        ......
    </body> 
    </html> 
    </xsl:template>
</xsl:stylesheet> 

当我查看页面源时,节点“employee”及其子节点在那里,它们只是没有显示在html页面中。我认为这是因为我将输出方法指定为'html'。但是我必须生成一个html页面并将一些xml格式的节点嵌入到我的页面中......

我一直在尝试但失败了......有人能给我一些帮助吗?谢谢!

我希望输出页面是: enter image description here

3 个答案:

答案 0 :(得分:3)

如果浏览器要显示<employee>(尖括号和全部),则转换的序列化输出必须为&lt;employee&gt;。 XSLT 3.0具有允许您执行的功能

<xsl:value-of select="serialize(emp)"/>

这会让你想要你想要的;一些其他处理器可以将其作为扩展功能提供。如果没有,您可以使用用XSLT编写的序列化程序,例如:http://fgeorges.org/xslt/serial/或其中一个列出的序列化程序:http://www.mhonarc.org/archive/html/xsl-list/2010-08/msg00186.html

答案 1 :(得分:3)

这可能有点晚了,但我最终在这个页面中寻找完全相同的东西。

通过XLST在HTML页面上复制XML数据的一种非常简单的方法是使用框架。我找到了这个解决方案here,显然它已经过时并且已弃用,但我已经过测试并且已经开始工作了。

<xmp>
    <xsl:copy-of select="."/>
</xmp>

从屏幕截图中可以看出,我在下面有一个很好的手风琴和XML数据! enter image description here

答案 2 :(得分:2)

您可以考虑使用<textarea>元素并应用相同的样式属性来设置背景颜色,并利用一些JavaScript(例如jQuery Autosize)让textarea自动调整以适应内容:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>

    <xsl:template match="/">
        <html>
            <head>
                <title>Example of Employee Data</title>
                <script src='http://www.jacklmoore.com/js/jquery.js'></script>
                <script src='http://www.jacklmoore.com/js/jquery.autosize.js'></script>
                <script type="text/javascript">
                    $(document).ready(function(){
                        $('textarea').autosize();   
                    });
                </script>
            </head>  
            <body>
                <h2>The following shows the structure of employee data file: </h2>
                <textarea style="background-color: grey; width:100%">
                    <xsl:text>&#xa;</xsl:text>
                    <xsl:copy-of select="employees/employee"/>
                </textarea>
                ......
            </body> 
        </html> 
    </xsl:template>
</xsl:stylesheet>