zl程序教程

您现在的位置是:首页 >  其他

当前栏目

SAP ABAP实用技巧介绍系列之 使用XSLT替换xml中指定node的value

SAPNodeXML 介绍 系列 指定 替换 value
2023-09-14 09:02:51 时间

Created by Jerry Wang, last modified on Jun 30, 2014

用于测试的xml:

<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>

需求是将xml 文件中所有名为title的node的value替换成一个hard code value.
xslt program:

<xsl:stylesheet version="1.0"
xmlns:sap="http://www.sap.com/sapxsl"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" indent="no" method="xml" omit-xml-declaration="yes" version="1.0"/>
<xsl:template match="/">
 <catalog>
    <xsl:for-each select="catalog/cd">
    <cd>
      <xsl:for-each select="./*">
       <xsl:choose>
         <xsl:when test="name()='title'">
         <xsl:copy>
         <xsl:value-of select="'replaced!!!!'"/>
         </xsl:copy>
         </xsl:when>
         <xsl:otherwise>
           <xsl:copy>
              <xsl:value-of select="."/>
           </xsl:copy>
         </xsl:otherwise>
       </xsl:choose>
      </xsl:for-each>
    </cd>
    </xsl:for-each>
</catalog>
</xsl:template>
</xsl:stylesheet>

测试结果:
clipboard1
如果原始的xml里存在不需要替换值的xml node:
clipboard2
只需要添加一对应的for each即可:
clipboard3
注意:若xml 源文件里节点名称包含namespace:
clipboard4
则这些namespace必须显式定义在xslt中,同时在使用node 名称匹配时也需要加上namespace前缀:
clipboard5