Use XSLT to modify elements embedded in text of other elements
Since I would probably botch up the terminology, I'll explain by example.
My XML source document contains elements like this:
<paragraph>
This paragraph has things like <link><xref label="lbl1">this</xref></link>
and things like <emphasis type="bold">this</emphasis>
and <emphasis type="italic">this</emphasis>.
</paragraph>
Need to use XSLT to transform that to:
<p>
This paragraph has things like <a href="[lbl1]">this</a>
and things like <b>th开发者_开发百科is</b>
and <i>this</i>.
</p>
Thanks!!
The current two solutions are too-long and one of them is not even well-formed XML...
Here is a short and complete solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="link">
<a href="[{xref/@label}]">
<xsl:apply-templates/>
</a>
</xsl:template>
<xsl:template match="emphasis">
<xsl:element name="{substring(@type,1,1)}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="xref">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<paragraph>This paragraph has things like <link><xref label="lbl1">this</xref></link> and things like <emphasis type="bold">this</emphasis> and <emphasis type="italic">this</emphasis>.
</paragraph>
the wanted, correct result is produced:
<paragraph>This paragraph has things like <a href="[lbl1]">this</a> and things like <b>this</b> and <i>this</i>.
</paragraph>
This should do the trick:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="paragraph">
<xsl:element name="p">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="link">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="xref">
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:text>[</xsl:text><xsl:value-of select="@label" /><xsl:text>]</xsl:text>
</xsl:attribute>
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="emphasis">
<xsl:variable name="elementName">
<xsl:choose>
<xsl:when test="@type='bold'">
<xsl:text>b</xsl:text>
</xsl:when>
<xsl:when test="@type='italic'">
<xsl:text>i</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:if test="string-length($elementName)>0">
<xsl:element name="{$elementName}">
<xsl:apply-templates />
</xsl:element>
</xsl:if>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
精彩评论