【问题标题】:how to Replace(dynamic) a specfic xml element using xsl如何使用 xsl 替换(动态)特定的 xml 元素
【发布时间】:2021-09-26 21:52:44
【问题描述】:

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

【问题讨论】:

  • 不清楚您所说的“删除特定标签”是什么意思。 XSL 转换中没有标签,只有节点。请编辑您的问题并添加预期结果。同时显示您当前的 XSLT 尝试,以便我们可以修复它,而不必从头开始为您编写代码。
  • @michael,我正在学习 xsl
  • 投票结束。
  • 我已经添加了 xsl ,我已经尝试过

标签: xml xslt-1.0


【解决方案1】:
<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多