【发布时间】:2016-08-17 23:58:33
【问题描述】:
我有一个 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<category id="Cat1" owner="Team1">
<entry id="Ent1" owner="John">
<title>This is Entry 1</title>
</entry>
<entry id="Ent2" owner="Matt">
<title>This is Entry 2</title>
</entry>
</category>
<category id="Cat2" owner="Team2">
<entry id="Ent3" owner="Arnold">
<title>This is Entry 3</title>
</entry>
<entry id="Ent4" owner="Jim">
<title>This is Entry 4</title>
</entry>
</category>
</root>
对于每个 ENTRY 元素,我想根据其 @id 属性更改其 TITLE 子元素的值。我创建了以下 XSLT,它首先定义了一个映射...每个映射条目的键是我要更改其标题的元素的 @id。每个地图条目的值是我希望 TITLE 元素(它是 ENTRY 的子元素)的值变成的值:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- set up the map -->
<xsl:variable name="map">
<entry key="Ent1">Here is the first entry</entry>
<entry key="Ent2">Here is the second entry</entry>
<entry key="Ent3">Here is the third entry</entry>
<entry key="Ent4">Here is the fourth entry</entry>
</xsl:variable>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Problem area: use the key to set the attribute of the correct procedure -->
<xsl:template match="entry">
<title><xsl:value-of select="$map/entry[@key = current()/@id]"/></title>
</xsl:template>
</xsl:stylesheet>
据我了解,这是一个两步过程:
- 执行身份转换
- 创建新模板以更改 TITLE 元素
但这会产生一个奇怪的输出,它用 TITLE 元素替换了我的整个 ENTRY 元素......好像所有的东西都执行得太高了 1 步。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<category id="Cat1">
<title>Here is the first entry</title>
<title>Here is the second entry</title>
<title>Here is the third entry</title>
</category>
<category id="Cat2">
<title>Here is the fourth entry</title>
<title>Here is the fifth entry</title>
<title>Here is the sixth entry</title>
</category>
</root>
我的地图有什么问题吗?我是否误解了身份转换后必须使用的新模板?
【问题讨论】:
-
你能发布转换输入示例的预期结果吗?