【问题标题】:Modify existing element of XML based on attribute value根据属性值修改 XML 的现有元素
【发布时间】:2019-02-12 06:33:30
【问题描述】:

我想使用 XSLT 根据属性值更新 XML 中的值,下面是输入和输出 XML

在本例中,我想在输入字符串中附加硬编码值。

输入 XML

<MyInfo isSurname="true">
    <name sysid="0">Google</name>
</MyInfo>

输出 XML

<MyInfo isSurname="true" surname="Drive">
    <name sysid="0">Google Drive</name>
</MyInfo>

对于每个输入名称姓氏将是相同的。所以当属性 isSurname 为真时,我们需要添加“Drive”作为姓

【问题讨论】:

  • 请提供minimal reproducible example。谢谢。
  • 这个姓氏值来自哪里?
  • 谢谢,这是一个常数值,因此我们可以对其进行硬编码。

标签: xml xslt xml-parsing


【解决方案1】:

让我们将你的 Input XML 放在根节点中,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <MyInfo isSurname="true">
       <name sysid="0">Google</name>
   </MyInfo>
</Root>

XSLT 1.0中的解决方案,可以是:

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

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

<xsl:template match="/Root/MyInfo">
    <xsl:choose>
        <xsl:when test="@isSurname = 'true'">
            <xsl:copy>
                <xsl:attribute name="surname">
                    <xsl:value-of select="'Drive'" />
                </xsl:attribute>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="/Root/MyInfo[@isSurname = 'true']/name/text()">
    <xsl:value-of select="concat(.,' Drive')" />
</xsl:template>

有一个基于isSurname 属性的检查。

  • 如果是true,那么会填充你给的Output XML
  • 如果是false,则输入XML将按原样显示。

【讨论】:

    【解决方案2】:

    这适用于您的简短示例 - 不确定这些是否是您要应用的一般规则:

    <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="*"/>
    
    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="@isSurname[.='true']">
        <xsl:copy/>
        <xsl:attribute name="surname">Drive</xsl:attribute>
    </xsl:template>
    
    <xsl:template match="name[../@isSurname='true']/text()">
        <xsl:copy/>
        <xsl:text> Drive</xsl:text>
    </xsl:template>
    
    </xsl:stylesheet>   
    

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多