XSLT:如何按属性条件'filter' xml 节点及其所有后代?



我在某些节点中有带有层属性的XML代码。 我想复制所有XML内容,但没有节点(及其所有后代( 图层大于图层参数。

在下面的示例中,图层参数获取值 2, 我希望所有具有第 3 层属性及其后代的元素都不应复制到新的 XML。

XSLT:

<?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" encoding="UTF-8" indent="yes"/>
<xsl:param name="layer" select="2"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@layer">
<xsl:if test="current() &lt;=  $layer">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

输入 xml:

<condition>
<caseCond>Yes</caseCond>
<inform layer="1">
<para>layer 1 information</para>
</inform>
<procContent>
<inform layer="2">
<para>layer 2 information</para>
</inform>
<comment layer="2">
<para>layer 2 information</para>
<para layer="3">layer 3 information</para>
</comment>
</procContent>
<endOfProc/>
</condition>

预期成果:

<condition>
<caseCond>Yes</caseCond>
<inform layer="1">
<para>layer 1 information</para>
</inform>
<procContent>
<inform layer="2">
<para>layer 2 information</para>
</inform>
<comment layer="2">
<para>layer 2 information</para>
</comment>
</procContent>
<endOfProc/>
</condition>

当前结果:

<?xml version="1.0" encoding="UTF-8"?>
<condition>
<caseCond>Yes</caseCond>
<inform layer="1">
<para>layer 1 information</para>
</inform>
<procContent>
<inform>
<para>layer 2 information</para>
</inform>
<comment>
<para>layer 2 information</para>
<para>layer 3 information</para>
</comment>
</procContent>
<endOfProc/>
</condition>

因此,通知标记中仅存在layer="1">表达式, 但是从所有包含的标签中删除了layer="2">表达式,

最重要的是,<para layer="3">layer 3 information</para>行仍然存在。

而我希望所有带有 layer=3 属性的标签及其后代都不会出现。

基于您的@layerparm参数

<?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" encoding="UTF-8" indent="yes"/>
<xsl:param name="layerparm" select="2"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[@layer > number($layerparm)]"/>
</xsl:stylesheet>

试试这个:

<xsl:template match="para[@layer]"/>

完整代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output  method="xml"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="para[@layer]"/>
</xsl:stylesheet>

最新更新