繁体   English   中英

如何通过其属性值更改元素/标签值?

[英]How to change a element/tag value by its attribute value?

我有一个带有长长标签列表的XML代码,并且我想在每个元素“文本”中用各自的“表单”属性值替换其中的单词和标签。

例如,这是我的XML文件中的2个句子:

<messages>
    <text>
        <spelling form="Hello">Helo</spelling> I'll see you next <abrev form="week">wk</abrev> alright.
    </text>
    <text>
        <abrev form="Come on">cmon</abrev> get ready <spelling form="dude">dood</spelling>!
    </text>
</messages>

这是我正在寻找的输出:

Hello I'll see you next week alright.
Come on get ready dude!

有谁知道如何做到这一点?


到目前为止,这是我的XSL文件中的内容:

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

    <xsl:for-each select="messages/text">

        <xsl:call-template name="parse">

            <!-- this selects all the tags inside "text" (I think...) -->
            <xsl:with-param name="a" select="./*"/>

        </xsl:call-template>

    </xsl:for-each>
</xsl:template>

然后,我的函数“解析”:

<xsl:template name="parse">

    <!-- "a" is the text to parse -->
    <xsl:param name="a"/>

    <!-- return the value of "form" -->
    <xsl:value-of select="$a/@form"/>

</xsl:template>

现在,我的功能“ parse”还没有完成。 我不知道如何用“形式”值替换拼写错误的单词。

谢谢您的帮助!

假设您的文本中可能同时包含<abrev><spelling>元素(实际上是任何具有form属性的元素),并且您的真实XML格式正确,则可以使用此样式表将标记的文本替换为中的值form属性:

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

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:apply-templates  select="messages/text"/>
    </xsl:template>

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

如果将其应用于此输入:

<messages>
    <text>
        <spelling form="Hello">Helo</spelling> I'll see you next <abrev form="week">wk</abrev> alright.
    </text>
    <text>
        <spelling form="Come on">cmon</spelling> get ready <abrev form="dude">dood</abrev>!
    </text>
</messages>

您将获得以下输出:

    Hello I'll see you next week alright.

    Come on get ready dude!

您可以从标识模板开始,然后从那里为每个元素创建模板,以便可以控制其特定输出。 因此,例如,让text元素输出其文本,并运行spellingabrev元素的模板,后者输出其@form属性。

这样看起来像下面。

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

  <xsl:template match="messages">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="text">
    <xsl:apply-templates select="*|text()"/>
  </xsl:template>

  <xsl:template match="spelling">
    <xsl:value-of select="@form"/>
  </xsl:template>

  <xsl:template match="abrev">
    <xsl:value-of select="@form"/>
  </xsl:template>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM