how to get tag values from xml using xslt

2019-08-22 07:00发布

问题:

<block3>
    <tag>
        <name>113</name>
        <value>Nfeb</value>
    </tag>
    <tag>
        <name>108</name>
        <value>20234254321</value>
    </tag>
</block3>

Here in above xml we have two tags in block3. I don't want 108 tag, so I need to prepare a xslt in that I have to call only 113. How can i do that? Can anyone please help me!

回答1:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:template match="/*">
        <xsl:apply-templates select="tag[not(name = '108')]"/>
    </xsl:template>

    <xsl:template match="tag">
        <xsl:value-of select="
            concat(name, '+', value)
        "/>
    </xsl:template>
</xsl:stylesheet>

Result against your sample will be 113+Nfeb.

A personally hate for-each, but for clarity.

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/">
        <xsl:for-each select="block3/tag[not(name = '108')]">
            <xsl:value-of select="concat(name, '+', value)"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


回答2:

I would create two templates. One matching all <tag> elements which does what you want, this will hit case 113. And then another one overriding it, matching the specific cases which you want to skip.

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="tag">.....do stuff....</xsl:template>
  <xsl:template match="tag[name = '108']" />

</xsl:stylesheet>


标签: xml xslt