如何使用 xsl 替换(动态)特定的 xml 元素

时间:2021-07-19 07:57:22

标签: xml xslt-1.0

输入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 的新手

1 个答案:

答案 0 :(得分: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>
相关问题