【问题标题】:Replacing the content of an element by the value of an arbitrary attribute with XSLT 2.0使用 XSLT 2.0 将元素的内容替换为任意属性的值
【发布时间】:2014-06-29 04:18:46
【问题描述】:

如果元素具有此属性,我需要将元素的内容替换为任意属性的值。我需要使用 XSLT 工作表 (2.0) 来做到这一点,但我不知道如何才能做到这一点。

例如,假设我有这个 xml 文档。

<?xml version="1.0" encoding="UTF-8"?>
<document> 
  Hi my name is <tag-A flag="Bob">Leopold</tag-A>
  and I'm fond of <tag-B flag="coding">literature</tag-B>
  unless in the <tag-C whatever="evening">morning</tag-C>
</document>

然后,xslt 将更改任何具有flag 属性的元素的内容,比如说,对于该属性的值,并将所有内容放在&lt;p&gt; 标记中。这是我在这种情况下会得到的输出。

<p>Hi my name is Bob
and I'm fond of coding
unless in the morning</p>

我怎么能做这样的事?

【问题讨论】:

  • 您的示例不会“替换标签的内容” - 它会用给定属性的值替换整个元素。无论如何,这似乎是一个非常基本的 XSLT 任务。你到底有什么困难?
  • 对不起,我的意思是元素。 -edited- 是的,我知道这可能是基本的 xslt,但是,我昨天开始学习 xslt 并且不知道如何完成它。 获取标志属性的所有值,可以,但是呢?我什至不知道从哪里开始诚实。

标签: xml xslt xslt-2.0


【解决方案1】:

这会产生您一直要求的输出:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes"/>

<xsl:template match = "document">
  <p><xsl:apply-templates select="node()"/>
  </p>
</xsl:template>

<xsl:template match = "*[@flag]">
  <xsl:value-of select="@flag"/>
</xsl:template>

</xsl:stylesheet>

请注意,@whatever 很高兴被忽略,但可以轻松折叠。

另外,我认为您不会对以

作为其最外层元素的文档感到满意?

【讨论】:

  • 啊啊啊我明白了,我不太明白如何使用模板。

    元素仅用于示例:P。这实际上是我正在做的一件相当复杂的事情。非常感谢!

  • 除了示例中的第三个属性是“whatever”而不是“flag”...是打算替换任何属性还是仅替换“flag”属性?
【解决方案2】:

注意:不清楚您的意思是什么,因为问题标题说“任意”,然后问题中的文本说“标志”属性。如果您的 XML 仅显示,并且您想用 any 属性替换并且您只有一个,则可以这样做(只需要 XSL 1.0):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:template match="document">
       <p>
        <xsl:apply-templates/>
       </p>
    </xsl:template>
    <xsl:template match="node()">
        <xsl:apply-templates select="@*"/>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:copy/>
    </xsl:template>
    </xsl:stylesheet>

XML 的输出是:

<p> 
Hi my name is Bob
and I'm fond of coding
unless in the evening
</p>

【讨论】:

  • 如果帖子只替换“标志”属性,这是行不通的。目前尚不清楚是否只有“标志”或任何属性是要求。
  • 如果您将node() 替换为element(),您甚至可以省略最后一个模板。 - 我也不太确定属性的名称。
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
相关资源
最近更新 更多