简体   繁体   中英

XSLT suppress all nodes except one

Say I've an xml document. I want to suppress output of all nodes except one (here in example the node with nodename name ).

<xsl:template match="/">
<html>
  <body>
    <h2>Heading</h2>
    <xsl:apply-templates />
  </body>
</html>
</xsl:template>

<xsl:template match="group">
    <h3>Group</h3>
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="*">
  <!-- No output for all -->
</xsl:template>

<xsl:template match="name">
    <div class="block">
    Name: <xsl:value-of select="concat(@first, ' ', @middle, ' ', @last)" />
</xsl:template>

This is my sample XML

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="visualization.xsl"?>
<group>
<student>
    <name first="Some" last="One" middle="_"></name>
    <dob>
        <date>30</date>
        <month>Feb</month>
        <year>1987</year>
    </dob>
    <nationality>NoMansLand'ian</nationality>
    <gender>male</gender>
</student>
</group>

But this way it prints the values inside the nodes. So I get output of 30 Feb 1987 NoMansLand'ian male .

Why The empty template for mach = '*' doesn't suppress any output at all ?
Do I need to Eat the output in some expression inside that blank template ?

What is the generic way to achieve this ?

<xsl:template match="*"> is catching the elements and which don't have specific template matches (eg gender, dob, nationality) and is applying default processing to their text child nodes.

Add one template to catch and filter these elements which doesn't processing their text children:

 <xsl:template match="dob | nationality | gender"/>

Another way, given the structure of the xml would be to ensure that student children are processed and filter, but only process the nodes we want:

 <xsl:template match="student/*"/>    <!-- do nothing  -->

 <xsl:template match="student/name">
    <xsl:apply-templates/>            <!-- do something  -->
 </xsl:template>

Like deanosaur said, it's because of the default processing of the text() nodes (see http://www.w3.org/TR/xslt#built-in-rule ).

Try replacing your match="*" with match="text()" ...

<xsl:template match="text()"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM