递归复制 xml 的一部分,并在副本上应用模板



我有下一个XML。下一个问题。我为weneedit节点的孩子制作了寺庙。我需要删除所有排除Weneedit和他的孩子。我无法应用模板并一起制作递归副本。

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <list>
    <element>
      <subelement>123</subelement>
    </element>
    <element>
    <subelement>
      <weneedit>
        <andit>
          <helpfultext>
          </helpfultext>
        </andit>
      </weneedit>
    </subelement>
    </element>
  </list>
  <tag>
  <rt>321</rt>
  </tag>
</root>

我试过这样做

<xsl:stylesheet version="2.0"
xpath-default-namespace="http://www.w3.org/1999/xhtml"
xmlns:n="http://www.example.com/example/example.xsd" >
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="n:weneedit">
    <xsl:copy-of select="parent::node()"/>
</xsl:template>
</xsl:stylesheet>

但不能一起使用一个或另一个模板

我想得到这样的东西

<subelement>
  <weneedit>
    <andit>
      <helpfultext>it was edited</helpfultext>
    </andit>
  </weneedit>
</subelement>

我不确定我是否理解你的问题。以下样式表:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="/root">
    <xsl:apply-templates select="list/element/subelement[weneedit]"/>
</xsl:template>
</xsl:stylesheet>

将导致:

<?xml version="1.0" encoding="UTF-8"?>
<subelement>
  <weneedit>
    <andit>
      <helpfultext/>
    </andit>
  </weneedit>
</subelement>

您可以添加其他模板来处理包含的节点,例如 <helpfultext> .

请注意,这假设只有一个包含<weneedit><subelement>;否则您的结果将有多个根元素,这在 XML 中是不允许的。

相关内容

最新更新