Frage

I am trying to transform HTML to XML using XSLT:

HTML:

<html>
<body>
    <p class="one">Some paragraph 1.</p>
    <p class="one">Some paragraph 2.</p>
    <p class="one">Some paragraph 3  with <em>em</em>.</p>
    <p class="one">Some paragraph 4.</p>
    <p class="one">Some paragraph 5.</p>
    <h3>Some heading</h3>
    <p class="two">Some other paragraph 1 with <em>em</em>.</p>
    <p class="two">Some other paragraph 2.</p>
    <p class="two">Some other paragraph 3.</p>
    <p class="two">Some other paragraph 4.</p>
    <p class="two">Some other paragraph 5.</p>
</body>
</html>

Desired output:

Some paragraph 1.
Some paragraph 2.
Some paragraph 3  with <emphasis>em</emphasis>.
Some paragraph 4.
Some paragraph 5.
Some heading
<paragraph>Some other paragraph 1 with <emphasis>em</emphasis>.</paragraph>
<paragraph>Some other paragraph 2.</paragraph>
<paragraph>Some other paragraph 3.</paragraph>
<paragraph>Some other paragraph 4.</paragraph>
<paragraph>Some other paragraph 5.</paragraph>

XSLT:

<xsl:output indent="yes" />


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

<xsl:template match="em">
    <emphasis><xsl:value-of select="."/></emphasis>
</xsl:template> 

<xsl:template match="p[@class='two']">
    <paragraph><xsl:value-of select="."/></paragraph>
</xsl:template> 

Output of this XSLT tranformation:

Some paragraph 1.
Some paragraph 2.
Some paragraph 3  with <emphasis>em</emphasis>.
Some paragraph 4.
Some paragraph 5.
Some heading
<paragraph>Some other paragraph 1 with em.</paragraph>
<paragraph>Some other paragraph 2.</paragraph>
<paragraph>Some other paragraph 3.</paragraph>
<paragraph>Some other paragraph 4.</paragraph>
<paragraph>Some other paragraph 5.</paragraph>

Template for em element seems to work fine when no other template is defined for parent element (p.one). However, when there is template for parent element (p.two), template for child (em) element seems to get ignored by tranformation and instead of getting:

<paragraph>Some other paragraph 1 with <emphasis>em</emphasis>.</paragraph>

I get:

<paragraph>Some other paragraph 1 with em.</paragraph>

Why is XSLT ignoring template for em element in this case?

War es hilfreich?

Lösung

It's getting ignored because you are simply printing out the value with:

<paragraph><xsl:value-of select="."/></paragraph>

If you want the em template to be applied on the contents of the p[@class='two'] template, then you should replace it with:

<xsl:template match="p[@class='two']">
    <paragraph><xsl:apply-templates /></paragraph>
</xsl:template> 

Now the contents of <paragraph> will be processed in a template if there is one (not simply converted into text and printed out).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top