我有一个输入 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/