輸入xml檔案:
<root>
<x1 attr11="sd5">
<x2 attr12="sd6" attr15="sd7">
<a />
<b>
<x3 attr18="sd8">
<c>
<x4 attr19="sd9"/>
<d />
<e />
</c>
</x3>
</b>
</x2>
</x1>
</root>
從中獲取更新的“updates.xml”檔案 - 標記屬性:
<updates>
<a attr1="adf" attr2="67" />
<b attr3="g6h"/>
<c attr4="7jj" />
<d attr5="88" attr6="mn4" />
<e />
</updates>
如果輸入檔案包含來自“updates.xml”檔案的標簽(沒有屬性),則將“updates.xml”檔案中的屬性復制到其中。XSLT1.0 轉換后的檔案應如下所示:
<root>
<x1 attr11="sd5">
<x2 attr12="sd6" attr15="sd7">
<a attr1="adf" attr2="67" />
<b attr3="g6h">
<x3 attr18="sd8">
<c attr4="7jj">
<x4 attr19="sd9"/>
<d attr5="88" attr6="mn4" />
<e />
</c>
</x3>
</b>
</x2>
</x1>
</root>
現在這是 XSLT1.0 轉換檔案:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exslt="http://exslt.org/common"
exclude-result-prefixes="exslt"
version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:param name="updates" select="document('updates.xml')"/>
<xsl:key name="replacement" match="//*" use="local-name()"/>
<!--Identity template-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(node())]">
<xsl:variable name="element" select="(.)"/>
<xsl:variable name="replacement">
<xsl:for-each select="$updates">
<xsl:copy-of select="key('replacement', local-name($element))"/>
</xsl:for-each>
</xsl:variable>
<xsl:choose>
<xsl:when test="exslt:node-set($replacement)/*">
<xsl:copy-of select="$replacement"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="(.)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
轉換后的 XML 檔案:
<root>
<x1 attr11="sd5">
<x2 attr12="sd6" attr15="sd7">
<a attr1="adf" attr2="67" />
<b>
<x3 attr18="sd8">
<c>
<x4 attr19="sd9" />
<d attr5="88" attr6="mn4" />
<e />
</c>
</x3>
</b>
</x2>
</x1>
</root>
為什么不將屬性復制到“b”和“c”標簽?
uj5u.com熱心網友回復:
使用(即身份轉換)處理原始屬性以及來自其他檔案的屬性apply-templates并保持遞回處理:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exslt="http://exslt.org/common"
exclude-result-prefixes="exslt"
version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:param name="updates" select="document('updates.xml')"/>
<xsl:key name="replacement" match="*" use="local-name()"/>
<!--Identity template-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:variable name="this" select="."/>
<xsl:for-each select="$updates">
<xsl:apply-templates select="key('replacement', local-name($this))/@*"/>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452396.html
下一篇:如何跟蹤從模板到不同模板的位置?
