首页 > 解决方案 > 如何使用 xsl 替换(动态)特定的 xml 元素

问题描述

输入 xml 这是输入 XML。

<?xml version="1.0" encoding="UTF-8"?>
<enc xmlns="v9">
   <rnp xmsns="v2">
      <ele1 line="1">
         <ele2/>
      </ele1>
   </rnp>
   <Request xmlns="v1">
      <Request xmlns="v2">
         <Info xmlns="v3">
            <Country>US</Country>
            <Part>A</Part>
         </Info>
      </Request>
   </Request>
</enc>

我想用 v2 标签替换“Request with namespce v1”。

XSL:这是我用过的 xsl。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
    <xsl:variable name="var1">
        <xsl:value-of select="local-name()"/>
        </xsl:variable>
        <xsl:copy>
        <xsl:choose>
        
            <xsl:when test="$var1='Request'">
                <xsl:element name="{local-name()}" namespace="v2">
          <xsl:apply-templates select="@* | node()"/>
      </xsl:element>
            </xsl:when>
            <xsl:otherwise>
             <xsl:apply-templates select="@*|node()"/> 
            </xsl:otherwise>
             </xsl:choose>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

在此先感谢。我是 xsl 的新手

标签: xmlxslt-1.0

解决方案


<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:v1="v1"
  exclude-result-prefixes="v1">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <!--  You namespaces do not have a prefix, just the URL.  So v1 would be considered 
        the URL (even though it doesn't look like one).  So, you have to declare your 
        namespace like I have above.  And, use the prefix in the template match.  
        Also, after transformation the child Request node will not have the v2 
        namespace shown because it inherits it from the parent Request node that was 
        just changed.  But, it is in the namespace.
  -->

  <xsl:template match="v1:Request">
    <xsl:element name="Request" namespace="v2">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>

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

</xsl:stylesheet>

推荐阅读