XSLT 删除与正则表达式不匹配的元素 [英] XSLT remove elements that do not match regex

查看:32
本文介绍了XSLT 删除与正则表达式不匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的 XSLT,它只会保留包含某个正则表达式的元素:

I want a simple XSLT which will only keep the elements which contain a certain regex:

<example>
  <abc>text</abc>
  <bc>text</bc>
  <ab>text</ab>
</example>

我想要相同的 XML 输出,但只需要包含a"的元素:

I want the same XML output but only with the elements which contain an "a":

<example>
  <abc>text</abc>
  <ab>text</ab>
</example>

推荐答案

从身份转换开始并添加一个模板来抑制名称与您的正则表达式不匹配的元素:

Start with the identity transform and add a template that suppresses elements whose name does not match your regex:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="*[not(matches(name(), 'a'))]"/>

</xsl:stylesheet>

说明:默认情况下,身份转换会将所有内容按原样复制到输出.通过编写一个简单的模板来覆盖这个默认行为,该模板匹配名称中没有a"的元素并且什么都不做,从而防止这些元素出现在输出文档中.

Explanation: By default the identity transformation will copy everything over to the output as-is. Override this default behavior by writing a simple template that matches elements without "a" in their name and does nothing, thereby preventing such elements from appearing in the output document.

这篇关于XSLT 删除与正则表达式不匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆