首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XSLT -复制除特定子元素以外的所有子元素。

XSLT -复制除特定子元素以外的所有子元素。
EN

Stack Overflow用户
提问于 2022-07-14 18:54:37
回答 1查看 40关注 0票数 0

除了一个元素之外,我如何复制元素的所有子元素?我研究了几个例子,但这个解决方案在我的情况下显然行不通。

示例输入:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff attrib="select" id="1001">
        <name>should-1</name>
        <role>copy-1</role>
    </staff>
    <staff id="1002">
        <name>should-3</name>
        <role>not-copy-3</role>
    </staff>
    <staff attrib="select" id="1003">
        <name>should-2</name>
        <role>copy-2</role>
    </staff>
</company>

预期产出:因此,不包括:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<staff attrib="select" id="1001">
    <name>should-1</name>
</staff>
<staff id="1002">
    <name>should-3</name>
</staff>
<staff attrib="select" id="1003">
    <name>should-2</name>
</staff>

我的XSLT脚本:尝试了很多次,但没有成功。

代码语言:javascript
复制
<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"/>

<!-- try 1 --> 
<xsl:template match="/company/staff/role" />

<!-- try 2 --> 
<xsl:template match="role" />

<!-- try 3 --> 
<xsl:template match="//role" />

<xsl:template match="/company">
    <parent>
        <xsl:copy-of select="staff"/>
    </parent>
</xsl:template>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-14 19:39:45

你可以这样做:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>
  
  <!-- Remove all role elements -->
  <xsl:template match="role"/>
  
  <!-- Identity transform -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

标识转换复制所有内容,角色模板捕获所有角色元素并对它们不做任何操作,从而有效地删除它们。

看到它在这里工作:https://xsltfiddle.liberty-development.net/3N7DtjK

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72985396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档