簡體   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