[英]Copy child nodes with exeptions in 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.