用于测试的xml:
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
需求是将xml 文件中所有名为title的node的value替换成一个hard code value. xslt program:
<xsl:stylesheet version="1.0"
xmlns:sap="http://www.sap.com/sapxsl"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" indent="no" method="xml" omit-xml-declaration="yes" version="1.0"/>
<xsl:template match="/">
<catalog>
<xsl:for-each select="catalog/cd">
<cd>
<xsl:for-each select="./*">
<xsl:choose>
<xsl:when test="name()='title'">
<xsl:copy>
<xsl:value-of select="'replaced!!!!'"/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</cd>
</xsl:for-each>
</catalog>
</xsl:template>
</xsl:stylesheet>
测试结果:
如果原始的xml里存在不需要替换值的xml node:
只需要添加一对应的for each即可:
注意:若xml 源文件里节点名称包含namespace:
则这些namespace必须显式定义在xslt中,同时在使用node 名称匹配时也需要加上namespace前缀: