My xml is
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<countries>
<country name="india">
<name>Rajan</name>
<pop>90.09</pop>
<car>Audi</car>
</country>
<country name="japan">
<name>Yenhovong</name>
<pop>172</pop>
<car>Sumo</car>
</country>
</countries开发者_运维百科>
Here i want display the elements of
country name="japan"
using xslt. But I dont know match the attribute in xslt. Help me, thanks in advance
The Xpath expression for it will be country[@name = 'japan']
.
XML
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<countries>
<country name="india">
<name>Rajan</name>
<pop>90.09</pop>
<car>Audi</car>
</country>
<country name="japan">
<name>Yenhovong</name>
<pop>172</pop>
<car>Sumo</car>
</country>
</countries>
XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="country[@name = 'japan']">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="country"/>
</xsl:stylesheet>
RESULT
<?xml version="1.0" encoding="utf-8"?>
<country name="japan">
<name>Yenhovong</name>
<pop>172</pop>
<car>Sumo</car>
</country>
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(ancestor-or-self::country)]">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="country[not(@name='japan')]"/>
</xsl:stylesheet>
when applied on the provided XML document:
<countries>
<country name="india">
<name>Rajan</name>
<pop>90.09</pop>
<car>Audi</car>
</country>
<country name="japan">
<name>Yenhovong</name>
<pop>172</pop>
<car>Sumo</car>
</country>
</countries>
produces the wanted, correct result:
<country name="japan">
<name>Yenhovong</name>
<pop>172</pop>
<car>Sumo</car>
</country>
Do note:
The identity rule is used to copy every wanted node "as-is". The use and overriding of the identity template is the most fundamental XSLT design pattern.
A single template overrides the identity rule for any element that has a
country
ancestor or isn't itself acountry
element. Such elements are not copied to the output, but their children-nodes are processed.An overriding template matching any
country
element whosename
attribute is not'japan'
. This has empty body and this results in any such elements ignored/deleted/not-copied.The result of 1 to 3 above is that only a
country
element whosename
attribute is'japan'
is processed by the identity template and is copied to the output.
精彩评论