首页 > 解决方案 > XSLT 2.0 用 'and' 替换 xml 中所有出现的 '&'(如果有)

问题描述

我对 xslt 很陌生,需要一些字符串操作方面的帮助。我正在尝试在 xslt 上工作,我想在 xml 中用 'and' 替换所有出现的特殊字符 '&'。我尝试过的少数几件事之一

<xsl:template match="Model">
    <Model>
       <xsl:value-of select="replace(//P1/P2/Vehicles/Vehicle/Model, '&amp;','and')"/> 
    </Model>
</xsl:template>

如果只有一辆车,它工作正常,但如果有多辆车,它就不能工作。

xml:

<P1>
  <someNode>
  <P2>
    <Vehicles>
        <Vehicle>
           <Id>1</Id>
           <Make>My car</Make>
           <Model>my model & something</Model>
        </Vehicle>
        <Vehicle>
            <Id>2</Id>
            <Make>My car2</Make>
            <Model>my model2</Model>
        </Vehicle>
    </Vehicles>
  </P2>
 <P1>

非常感谢任何帮助。谢谢!

标签: xmlxslt-2.0

解决方案


提供的 XML 格式不正确。我不得不修复它。

XSLT 使用身份转换模式。

XML

<P1>
    <someNode/>
    <P2>
        <Vehicles>
            <Vehicle>
                <Id>1</Id>
                <Make>My car</Make>
                <Model>my model &amp; something</Model>
            </Vehicle>
            <Vehicle>
                <Id>2</Id>
                <Make>My car2</Make>
                <Model>dog &amp; pony</Model>
            </Vehicle>
        </Vehicles>
    </P2>
</P1>

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="Model">
        <xsl:copy>
            <xsl:value-of select="replace(., '&amp;','and')"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

推荐阅读