XSLT:copy-of 如何修改内容来替换某些元素?

2024-05-24

我有一个输入 XML 文档,如下所示:

<text>
    <p>
    Download the software from <link id="blah">
    </p>
</text>
    <links>
    <link id="blah">
    <url>http://blah</url>
    </link>
    </links>

我希望我的输出文档是:

<text>
    <p>
    Download the software from <a href="http://blah"> http://blah </a>
    </p>
</text>

也就是说:我想按原样复制现有的输入文档节点,但也替换某些节点(例如<link>)具有扩展版本:基于输入文档中包含的其他信息。

我尝试使用<xsl:copy .../>首先像这样复制片段:

<xsl:variable name="frag">
<xsl:copy-of select="text"/>
</xsl:variable>

但是当我像这样输出变量时:

<xsl:value-of select="$frag">

输出似乎没有保留段落标签?所以我不确定 xsl-copy 是否已复制节点,或者只是以某种方式复制文本?

如果我只输入以下内容(去掉<xsl:variable/>'wrapper'),它确实保留输出文档中的标签吗?

<xsl:copy-of select="text"/>

但当然,我需要首先将“链接”标签重新映射到锚标签......

我什至还没有开始弄清楚如何用链接信息替换变量的内容(当然是在新变量中)......


尝试这个 :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes"/>
    <xsl:template match="links"/>
    <xsl:template match="*|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="link">
        <xsl:variable name="link" select="normalize-space(//links/link[@id = current()/@id]/url)"/>
        <a href="{$link}">
            <xsl:value-of select="$link"/>
        </a>
    </xsl:template>
</xsl:stylesheet>

输入以下内容:

<?xml version="1.0" encoding="UTF-8"?>
    <texts>
        <text>
            <p>
                Download the software from <link id="blah"/>
            </p>
        </text>
        <links>
            <link id="blah">
                <url>http://blah</url>
            </link>
        </links>
    </texts>

你得到 :

<?xml version="1.0" encoding="UTF-8"?>
<texts>
    <text>
        <p>
            Download the software from <a href="http://blah">http://blah</a>
        </p>
    </text>
</texts>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XSLT:copy-of 如何修改内容来替换某些元素? 的相关文章

随机推荐