我正在尝试使用XML&amp ;;输出表单php中的XSLT,但我无法以某种方式满足条件。我的XML看起来像是什么:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="form.xsl"?>
<root>
<formset>
<field>
<type>text</type>
<value>This is test value</value>
</field>
<field>
<type>radio</type>
<value>Male</value>
</field>
<field>
<type>checkbox</type>
<value>Hobby</value>
</field>
<field>
<type>button</type>
<value>Click Me</value>
</field>
</formset>
</root>
这是我的XSLT文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Rendering of Form</title>
</head>
<body>
<form action="" method="post">
<xsl:for-each select="/root/formset/field">
<xsl:choose>
<xsl:when test="type = text">
<input type="text" value="{value}" />
</xsl:when>
<xsl:when test="type = radio">
<input type="radio" value="{value}" /> <xsl:value-of select="value"/>
</xsl:when>
<xsl:when test="type = checkbox">
<input type="checkbox" value="{value}" /> <xsl:value-of select="value"/>
</xsl:when>
<xsl:when test="type = button">
<input type="button" value="{value}" />
</xsl:when>
<xsl:otherwise>
<span>Unknown Type</span>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</form>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我的PHP代码是这个简单的echo输出:
<?php
// LOAD XML FILE
$XML = new DOMDocument();
$XML->load('form.xml');
// START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load('form.xsl');
$xslt->importStylesheet( $XSL );
echo $xslt->transformToXML( $XML );
?>
但不知怎的,我的输出渲染xsl:otherwise
条件可以让任何人告诉我为什么?我是XSLT的新手
答案 0 :(得分:2)
这实际上与PHP无关,而只是与你在xsl中错过了一些撇号的事实有关:在测试语句时。你目前正在这样做
<xsl:when test="type = text">
但这是将名为 type 的元素与名为 text 的元素进行比较,该元素实际上并不存在于XML中。你需要这样做
<xsl:when test="type = 'text'">
即。您需要与包含在撇号中的文字字符串进行比较。
如果您热衷于学习XSLT,这里有一种方法可以做同样的事情而不需要 xsl:for-each xsl:choose
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Rendering of Form</title>
</head>
<body>
<form action="" method="post">
<xsl:apply-templates select="root/formset/field"/>
</form>
</body>
</html>
</xsl:template>
<xsl:template match="field">
<input type="{type}" value="{value}"/>
</xsl:template>
<xsl:template match="field[type != 'text'][type != 'radio'][type != 'checkbox'][type != 'button']">
<xsl:text>Unknown Type</xsl:text>
</xsl:template>
</xsl:stylesheet>
通常首选使用模板,因为它有助于重复使用代码,并减少缩进以使其更具可读性。请注意,匹配元素时,将始终首先选择更具体的模板。