XSLT remove elements that do not match regex

南楼画角 提交于 2021-02-17 04:44:41

问题


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>

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

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

回答1:


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>

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.



来源:https://stackoverflow.com/questions/36557941/xslt-remove-elements-that-do-not-match-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!