【问题标题】:How to handle the 'LOC_NAME' element value如何处理“LOC_NAME”元素值
【发布时间】:2021-05-24 09:12:40
【问题描述】:

在下面的示例中,我们尝试处理“LOC_NAME”元素的值,如果最后出现“前”字,那么我们将使用 xslt 1.0 删除:

谁能帮忙。

输入 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<LOC_NAME>Front</LOC_NAME>
<LOC_NAME>Arapaoa Front.</LOC_NAME>
<LOC_NAME>Arapaoa Island. Front</LOC_NAME>
<LOC_NAME>North Stake Front Stbd No.31</LOC_NAME>
<LOC_NAME>North Stake No.35</LOC_NAME>
</root>

预期输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<LOC_NAME>Front</LOC_NAME>
<LOC_NAME>Arapaoa</LOC_NAME>
<LOC_NAME>Arapaoa Island.</LOC_NAME>
<LOC_NAME>North Stake Front Stbd No.31</LOC_NAME>
<LOC_NAME>North Stake No.35</LOC_NAME>
</root>

XSLT 代码:

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

<xsl:template match="LOC_NAME">
<xsl:copy>
    <xsl:choose>
        <xsl:when test=".='Front'">
            <xsl:value-of select="'Front'"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:copy>    
</xsl:template>

</xsl:stylesheet>

参考网址# http://xsltransform.net/6qCcddQ/1

【问题讨论】:

  • @michael.hor257k - 很抱歉,很高兴向我推荐对我很有帮助的答案。
  • 您需要明确要修改哪些元素。"Front""Front." 不同。还能有其他变种吗?

标签: xml xslt xpath xslt-1.0 xquery


【解决方案1】:

您显示的结果可以通过以下方式实现:

XSLT 1.0

<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:template match="/root">
    <root>
        <xsl:for-each select="LOC_NAME">
            <xsl:variable name="len" select="string-length(.)" />
            <xsl:copy>
                <xsl:choose>
                    <xsl:when test="substring(., $len - 5)=' Front'">
                        <xsl:value-of select="substring(., 1, $len - 6)"/>
                    </xsl:when>
                    <xsl:when test="substring(., $len - 6)=' Front.'">
                        <xsl:value-of select="substring(., 1, $len - 7)"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="."/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:copy>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 谢谢迈克尔,建议的解决方案工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2019-07-03
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多