<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
和两个文件,每行都有要搜索的值,(file1)和替换文件(file2),
看起来像这样
文件1:
XML Developer's Guide
Midnight Rain
...
和file2(带替换):
self1. replacement title 1
self2. replacement title 2
...
我需要一个xslt文件的方法,
将所有匹配的标题元素替换为.
和空格
在xml文件<hold>
中创建一个新元素,该元素的信息位于.
和空格之前,因此结果应如下所示
输出xml文件:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>replacement title 1</title>
<hold>self1</hold>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>replacement title 2</title>
<hold>self2</hold>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
答案 0 :(得分:1)
让我们首先假设您已将参数文件转换为XML格式
<changes>
<change id="self1" from="XML Developer's Guide" to="replacement title 1"/>
<change id="self2" from="Midnight Rain" to="replacement title 2"/>
</changes>
这个XML是全局变量$ changes。
您现在可以使用身份模板和规则来实现转换:
<xsl:template match="title">
<xsl:variable name="replacement" select="$changes/change[@from=current()]"/>
<xsl:choose>
<xsl:when test="$replacement">
<title><xsl:value-of select="$replacement/@to"/></title>
<hold><xsl:value-of select="$replacement/@id"/></hold>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
剩下的就是构造参数文件的XML表示:
<xsl:variable name="$replacements">
<xsl:variable name="f1" select="tokenize(unparsed-text('file1.txt'), '\r?\n')"/>
<xsl:variable name="f2" select="tokenize(unparsed-text('file2.txt'), '\r?\n')"/>
<changes>
<xsl:for-each select="1 to count($f1)">
<xsl:variable name="i" select="."/>
<change id="{substring-before($f2[$i], '.')}"
from="{normalize-space($f1[$i])}"
to="{normalize-space(substring-after($f2[$i], '.'))}"/>
</xsl:for-each>
</changes>
</xsl:variable>