将XSLT转换为简单的HTML代码段

时间:2010-03-08 02:00:16

标签: xml xslt

XML

        <?xml version="1.0" encoding="utf-8" ?>
<data>
    <events />
    <tour>
        <section id="3" handle="tour">Tour</section>
        <entry id="15">
            <title handle="dummy-entry-1">Dummy Entry 1</title>
            <description mode="formatted">Lorem ipsum dolor sit amet...</description>
            <photo size="24 KB" path="/images/tour" type="image/jpeg">
                <filename>no-image.jpg</filename>
                <meta creation="2010-03-07T17:00:24-08:00" width="1000" height="1000" />
            </photo>
        </entry>
    </tour>
</data>

XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/data/tour/entry">
  <img src="{filename}"/>
  <h2>{heading}</h2>
  {description}
 </xsl:template>
</xsl:stylesheet>

这是我正在使用的代码。我是XSLT的新手,我想我不理解它如何将我的XML完全转换为HTML。我打算通过AJAX加载这段代码,所以我真的需要输出的是一个空白的html文档,只包含这三个项目。

我意识到我省略了xsl:output标签,这是因为我真的不明白我怎么能只是简单地将这些信息与我的xml中的标签匹配而不添加,标签等等。它的所有输出都是html文档中的一串文本。

如果有帮助,我在Symphony CMS环境中工作。

2 个答案:

答案 0 :(得分:1)

首先你必须添加这个

 <xsl:output method="html" encoding="UTF-8" indent="no"/>

它会告诉您的XSLT解析器您要输出HTML。

将一些内容从XML输出到HTML,你必须使用value-of

<xsl:value-of select="/xpath/of/xml"/>

根据您输出的复杂程度,您需要使用<xsl:template name="name">,它允许您在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" encoding="UTF-8" indent="no"/>
<xsl:template match="/">
  <xsl:variable name="filename" select="/data/tour/entry/photo/filename"/>
  <img src="{$filename}"/>
  <h2><xsl:value-of select="/data/tour/entry/title"/></h2>
  <xsl:value-of select="/data/tour/entry/description"/>
 </xsl:template>
</xsl:stylesheet>

希望这会有所帮助。

PHP代码段

<?php

$xml = new DOMDocument;

$xmlC = file_get_contents('data.xml');
$xml->loadXml( $xmlC);

$xsl = new DOMDocument();
$xsl->load('template.xlst');


// Configuration du transformateur
$proc = new XSLTProcessor();
$proc->importStyleSheet($xsl); // attachement des règles xsl
$proc->registerPHPFunctions();
header('Content-Type: text/xml');
echo $proc->transformToXML($xml);

PS:使用您的XML进行更新。我会尝试在PHP中查看它是否运行正常 PS2:更新了运行PHP示例和更新模板

答案 1 :(得分:0)

这最终成为了答案。我需要改变应用模板的方式。不确定为什么要修复它,但确实如此。

<?xml version="1.0" encoding="UTF-8"?>

    

<xsl:template match="/">
    <xsl:apply-templates select="data/tour-entry/entry" />
</xsl:template>

<xsl:template match="/data/tour-entry/entry">
    <img src="{$root}/image/2/675/300/5/images/tour/{photo/filename}" alt="" class="image" />
    <h2><xsl:value-of select="title"/></h2>
    <xsl:copy-of select="description"/>
    <script type="text/javascript">
        $(document).ready(function(){
            // How cufon applies our font to certain elements, styles based on css document.
            Cufon.replace('#content-main h2');
        });
    </script>   
</xsl:template>