【问题标题】:XSLT: Using a map to change child elementsXSLT:使用地图更改子元素
【发布时间】: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>

据我了解,这是一个两步过程:

  1. 执行身份转换
  2. 创建新模板以更改 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>

我的地图有什么问题吗?我是否误解了身份转换后必须使用的新模板?

【问题讨论】:

  • 你能发布转换输入示例的预期结果吗?

标签: xml xslt


【解决方案1】:

如果您想修改title 元素,那么您的模板应该匹配title - 而不是它的父元素entry

<xsl:template match="title">
    <title>
        <xsl:value-of select="$map/entry[@key = current()/../@id]"/>
    </title>
</xsl:template>

或者,您必须重新创建 entry 的内容,然后再继续到 title 子项:

<xsl:template match="entry">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <title>
            <xsl:value-of select="$map/entry[@key = current()/@id]"/>
        </title>
    </xsl:copy>
</xsl:template>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多