当我不知道节点的名称时,如何使用XSTL转换XML文档。所以基本上它应该普遍适用于任何XML文档。
假设我得到了这个 XML 文档:
<?xml version="1.0"?>
<?xml-stylesheet href="transform.xsl" type="text/xsl" ?>
<!DOCTYPE cinema [
<!ELEMENT a (b*)>
<!ELEMENT b (c,d,e)>
<!ELEMENT c (#PCDATA)>
<!ELEMENT d (#PCDATA)>
<!ELEMENT e (#PCDATA)>
]>
<cinema>
<movie>
<actor>Some actor</actor>
<title>Some title</title>
<year>Some year</year>
</movie>
</cinema>
我将如何从中创建 HTML 表?我知道我可以像这样匹配根元素:
<xsl:template match="/">
然后我选择所有这样的电影:
<xsl:for-each select="/*/*">
但是我怎么知道每部电影有三列演员、标题和年份?特别是因为XML文件(电影)应该只能有2个孩子或5个孩子。
+++编辑+++
如果我这样做:
<tr>
<td><xsl:value-of select="."/></td>
</tr>
我在一行中获取每部电影的详细信息。这几乎接近我想要实现的目标。但是如何将电影细节分散在该行的三列中呢?
如果你知道你总是有三个层次的元素(根,子和孙),那么这样的事情应该可以做到:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" />
<xsl:template match="/">
<html><body><xsl:apply-templates /></body></html>
</xsl:template>
<xsl:template match="/*">
<table><xsl:apply-templates /></table>
</xsl:template>
<xsl:template match="/*/*">
<tr><xsl:apply-templates /></tr>
</xsl:template>
<xsl:template match="/*/*/*">
<td><xsl:apply-templates /></td>
</xsl:template>
</xsl:stylesheet>
/
模板匹配文档节点,/*
匹配文档节点的第一级元素子元素(即文档的根元素),/*/*
匹配二级子元素等。
<xsl:apply-templates/>
(不带select
)会将匹配的模板应用于当前节点的所有子节点,其中包括子元素、文本节点、注释和处理指令。 因此,您可能需要根模板
<xsl:template match="/">
<html><body><xsl:apply-templates select="*" /></body></html>
</xsl:template>
以仅选择子元素。
示例 XML:
<?xml version="1.0" encoding="utf-8"?>
<cinema>
<movie>
<actor>Some actor</actor>
<title>Some title</title>
<year>Some year</year>
</movie>
<movie>
<actor>Someother actor</actor>
<title>Someother title</title>
<year>Someother year</year>
</movie>
</cinema>
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="xml" indent="yes"/>
<xsl:template match="/">
<table>
<xsl:for-each select="*/*">
<xsl:if test="position()=1">
<tr>
<th>actor</th>
<th>title</th>
<th>year</th>
</tr>
</xsl:if>
<tr>
<xsl:for-each select="actor|title|year">
<td>
<xsl:value-of select="."/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
输出:
<?xml version="1.0" encoding="utf-8"?>
<table>
<tr>
<th>actor</th>
<th>title</th>
<th>year</th>
</tr>
<tr>
<td>Some actor</td>
<td>Some title</td>
<td>Some year</td>
</tr>
<tr>
<td>Someother actor</td>
<td>Someother title</td>
<td>Someother year</td>
</tr>
</table>
使用:
<xsl:template match="movie">
<!-- Specify your tr-producing code here -->
</xsl:template>