【问题标题】:XSL: How to replace string AND change attribute valueXSL:如何替换字符串并更改属性值
【发布时间】:2016-09-02 08:37:22
【问题描述】:

我想实现更改属性值并用 XSL 替换元素的子字符串。

XML

<...>
   <communication type="telephone">123 456 789 </communication>
   <communication type="telephone">789 (EXT)</communication>
   <communication type="telephone">123 456 789 </communication>
</...>

应该是

<...>
   <communication type="telephone">123 456 789 </communication>
   <communication type="ext">789</communication>
   <communication type="telephone">123 456 789 </communication>
</...>

XSL (2.0)

<xsl:template match="communication[@type='telephone'][contains(text(),'(EXT)')]">
<xsl:copy>
    <xsl:value-of select="replace(., '(EXT)', '')"/>
    <xsl:attribute name="extension">true</xsl:attribute>
    <xsl:apply-templates select="@*|node()"/>
</xsl:copy>

撒克逊州 “在包含元素的子元素之后不能创建属性节点”

我没有实现更改属性类型的值,所以我创建了一个新属性。但即使使用这种解决方法,我也不知道如何使这两个要求(添加属性和删除子字符串)都起作用。

非常感谢任何解决此问题的想法!

【问题讨论】:

  • 您的标题显示“更改属性值”,并且您的输出显示您要将typeattribute 的值从“电话”更改为“分机”。但是您的代码正在添加一个新的 extension 属性。哪个是正确的?
  • 对此感到抱歉。我的意思是添加另一个具有相同值的属性“扩展”。

标签: xml xslt


【解决方案1】:

这部分:

<xsl:value-of select="replace(., '(EXT)', '')"/>

创建一个文本节点,它是communication 的子节点。完成此操作后,您将无法再创建 communication 的属性。您有两条说明可以尝试这样做:

<xsl:attribute name="extension">true</xsl:attribute>

和:

<xsl:apply-templates select="@*|node()"/>

@*)部分。

xsl:attribute 指令必须放在第一位 - 而且您真的不想在这里使用 xsl:apply-templates 指令,因为您已经自己创建了所有内容。

另请注意,您的 replace() 不会替换括号。

当然,您只需这样做就可以让这一切变得更简单:

<xsl:template match="communication[@type='telephone'][contains(text(),'(EXT)')]">
    <communication extension="true">
        <xsl:value-of select="replace(., '\(EXT\)', '')"/>
    </communication>
</xsl:template>

【讨论】:

    【解决方案2】:

    我想你想要

    <xsl:template match="communication[@type = 'telephone' and contains(., '(EXT)')]">
      <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="extension">true</xsl:attribute>
        <xsl:value-of select="replace(., '(EXT)', '')"/>
      </xsl:copy>
    </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2011-05-02
      • 1970-01-01
      相关资源
      最近更新 更多