[英]Match any node in XML document using XSLT even if I don't know the names of the nodes
當我不知道節點的名稱時,如何使用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>
/
template匹配文檔節點 , /*
匹配文檔節點的第一級元素子節點(即文檔的根元素), /*/*
匹配二級子節點等。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.