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

标签 xslt

我有一个输入 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/> '包装器'),它会保留输出文档中的标签吗?

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

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

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

最佳答案

试试这个:

<?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>

关于XSLT:copy-of 如何修改内容来替换某些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8271537/

相关文章:

XSLT 3 级属性分组

xslt - 如何写 <a href="mailto : tag in xslt?

xml - XSLT - XML (Word) 到 XSL-FO (PDF)

xml - 如何使用 xslt 从 xml 文件中选择语言节点

xslt - 基于节点值的 xsl 和 sibling

xml - 在 XPath 表示法中,表达式//*[self::SOME_LABEL] 与//SOME_LABEL 有何不同?

java - 无法从 jar 文件访问 xsl 文件 (Mule)

c++ - 在 C++ 中支持基于模式的不断发展的 XML 的技术

xml - XSLT - 如何按属性选择 XML 属性?

xslt - 如何使用 XSLT 在 <body> 中包含文件的所有内容?