xml - 在 XSLT 1.0 中复制带有异常的子节点
问题描述
我认为主要问题是如何编写 exeption 表达式来摆脱输出结果中的“S-3”和“Z”属性。但是怎么做?
源代码
<root>
<B att-1="some value" att-2="value"> text 1
<S-1>text 2</S-1>
<S-2>text 3</S-2>
<S-3 trash-att="value"> trash-text a </S-3>
<Z z-att="value"> z-text 1 </Z>
</B>
<B att-1="some value" att-2="value"> text 4
<S-1> text 5</S-1>
<S-2> text 6</S-2>
<S-3 trash-att="value"> trash-text b </S-3>
<Z z-att="value"> z-text 2 </Z>
</B>
<B att-1="some value" att-2="value"> text 7
<S-1> text 8</S-1>
<S-2> text 9</S-2>
<S-3 trash-att="value"> trash-text c </S-3>
<Z z-att="value"> z-text 3 </Z>
</B>
</root>
期望的输出
<root>
<B att-1="some value"
att-2="value"
S-1="text 2"
S-2="text 3">
<Z attr=" z-text 1 "/>
</B>
<B att-1="some value"
att-2="value"
S-1=" text 5"
S-2=" text 6">
<Z attr=" z-text 2 "/>
</B>
<B att-1="some value"
att-2="value"
S-1=" text 8"
S-2=" text 9">
<Z attr=" z-text 3 "/>
</B>
</root>
我的 xslt 代码(S-3 和 Z 属性仍然存在,但不应该) https://xsltfiddle.liberty-development.net/3NSTbfj/1
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<!-- 1 - MAIN transform with element B -->
<xsl:template match="B">
<B>
<xsl:copy-of select="@*"/>
<xsl:for-each select="*" >
<xsl:attribute name="{name()}">
<xsl:value-of select="text()"/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates select="@*|node()"/>
</B>
</xsl:template>
<!-- 2 - keep additional Z node -->
<xsl:template match="Z">
<Z >
<xsl:attribute name="attr">
<xsl:value-of select="."/>
</xsl:attribute>
</Z>
</xsl:template>
<!-- 3 - delete nodes -->
<xsl:template match="S-1">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="S-2">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="S-3">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
我将不胜感激任何解决方案
解决方案
你可以试试这个并使用 for-each
<?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" omit-xml-declaration="no" indent="yes"/>
<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates select="B"/>
</xsl:copy>
</xsl:template>
<xsl:template match="B">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:for-each select="*[not(@*)]">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates select="Z"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Z">
<xsl:copy>
<xsl:attribute name="attr">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>