[英]xpath is not working as expected in xslt
我有以下xml
<myRequest>
<id>123456789</id>
</myRequest>
我有以下xslt無法與輸出相同
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" encoding="ISO-8859-1" version="1.0"
omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="myRequest">
<myRequest>
<xsl:apply-templates select="id"/>
</myRequest>
</xsl:template>
<xsl:template match="id">
<customerId>
<xsl:value-of select="id"/>
</customerId>
</xsl:template>
</xsl:stylesheet>
工作xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" encoding="ISO-8859-1" version="1.0"
omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="myRequest">
<myRequest>
<xsl:apply-templates select="//id"/>
</myRequest>
</xsl:template>
<xsl:template match="id">
<customerId>
<xsl:value-of select="//id"/>
</customerId>
</xsl:template>
</xsl:stylesheet>
我將current()放在XWatch中,當插入調試指針時它也沒有顯示任何東西
<xsl:template match="myRequest">
<myRequest>
..........................
為什么我需要在這里使用// ?因為id元素直接位於myRequest下。我真的在這里使用//感到困惑?
不使用//也需要獲取輸出。
我在這里犯了什么錯誤?
提前致謝...
您的第一個模板需要看起來像這樣...
<xsl:template match="id">
<customerId>
<xsl:value-of select="."/>
</customerId>
</xsl:template>
xsl:value-of
的表達式將相對於您當前所在的節點( id
),因此通過執行<xsl:value-of select="id" />
您將查找一個名為id
的節點是當前id
元素的子級。 在做.
獲取當前節點的值。
//id
之所以起作用,是因為當您使用/
開頭表達式時,它將相對於頂級文檔節點,並且//
將在文檔中的任何位置搜索第一個id
。
注意,請考慮在XSLT身份模板上構建XSLT,因為這將使其更加通用,並能夠更改文檔中任何位置的id
元素。
試試這個XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" encoding="ISO-8859-1" version="1.0" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="id">
<customerId>
<xsl:apply-templates select="@*|node()"/>
</customerId>
</xsl:template>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.