我想在data-type='image'
存在时添加img
标签.我们可以做到是xslt 吗?
这是我的代码(http://xsltransform.net/pPJ8LVQ/3):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<hmtl>
<head>
<title>New Version!</title>
</head>
<xsl:for-each select=".//a/cd">
<li>
<strong>
<xsl:value-of select="title" />
</strong>
<div>
<xsl:copy-of select="body/node()" />
</div>
</li>
</xsl:for-each>
</hmtl>
</xsl:template>
<xsl:template match="div[@data-type = 'image']">
<img src="@src" />
</xsl:template>
</xsl:transform>
输入
<a>
<cd>
<title>dddd</title>
<body>
<div col="1">d<p>ddd</p></div>
</body>
</cd>
<cd>
<title>ccc</title>
<body>
<div col="1">iii<p>ddd</p>
<div data-type="image" src="abc.png" id='234'></div>
</div>
</body>
</cd>
</a>
预期产出
<li><strong>dddd</strong><div>
<div col="1">d
<p>ddd</p>
</div>
</div>
</li>
<li><strong>ccc</strong><div>
<div col="1">iii
<p>ddd</p>
<div id="234">
<img src="abc.png"/>
</div>
</div>
</div>
</li>
您需要
了解apply-templates
和模板匹配,然后转换元素:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<hmtl>
<head>
<title>New Version!</title>
</head>
<xsl:for-each select=".//a/cd">
<li>
<strong>
<xsl:value-of select="title" />
</strong>
<div>
<xsl:apply-templates select="body/node()" />
</div>
</li>
</xsl:for-each>
</hmtl>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="div[@data-type = 'image']">
<xsl:copy>
<xsl:apply-templates select="@* except (@data-type, @src)"/>
<img src="{@src}"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:transform>