【发布时间】:2015-01-30 17:32:14
【问题描述】:
我不确定标题是否正确。我有一个如下所示的 XML 文件:
XML 文件
<main>
<mainelement attribute="on">
<basic>23</basic>
random
<stuff id="10"/>
<a>sometext</a>
<b_1>1</b_1>
<b_2>0.300000</b_2>
<d att="one"/>
<e>value</e>
</mainelement>
<otherlement>
...
</otherlement>
</main>
我格式化文件以适应某个规范。标签 a-e 都是已知的和想要的。但也有可能里面还有其他不符合规范的东西。 (即基本的,随机的和东西)。我写了以下
XSL 脚本
<xsl:template match="main/mainelement">
<mainelement>
<xsl:copy-of select="a">
<xsl:variable name="b1" select="b_1"/>
<xsl:variable name="b2" select="b_2"/>
<b item1="{b1}" item2="{b2}">
<xsl:variable name="c" select="c"/>
<xsl:if test="$c">
<xsl:copy-of select="c">
</xsl:if>
<xsl:if test="not(c)">
<c>default</c>
</xsl:if>
<xsl:copy-of select="d">
<xsl:variable name="e" select="e"/>
<xsl:element name="e">
<xsl:attribute name="att">
<xsl:value-of select="$e">
</xsl:attribute>
</xsl:element>
</mainelement>
<!-- surrounds every element or text() that is unknown with the undefined-tag -->
<xsl:for-each select="* | text()">
<xsl:choose>
<xsl:when test="name()='a'"/>
<xsl:when test="name()='b_1'"/>
<xsl:when test="name()='b_2'"/>
<xsl:when test="name()='c'"/>
<xsl:when test="name()='d'"/>
<xsl:otherwise>
<undefined>
<xsl:copy-of select="current()"/>
</undefined>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
这几乎可以实现我想要实现的目标。问题是,我不知道除了规范之外是否有任何东西,如果上面没有基本、随机或东西之类的东西,那么根本就不应该有 标签。输出是
输出
<main>
<mainelement attribute="on">
<a>sometext</a>
<b item1="1" item2="0.3">
<c>default</c>
<d att="one"/>
<e att="value"/>
</mainelement>
<undefined>
<basic>23</basic>
</undefined>
<undefined>
random
</undefined>
<undefined>
<stuff id="10"/>
</undefined>
<otherlement>
...
</otherlement>
</main>
但我想做到这一点:
期望输出
<main>
<mainelement attribute="on">
<a>sometext</a>
<b item1="1" item2="0.3">
<c>default</c>
<d att="one"/>
<e att="value"/>
</mainelement>
<undefined>
<basic>23</basic>
random
<stuff id="10"/>
</undefined>
<otherlement>
...
</otherlement>
</main>
我想我想太多了,所以我对一个简单的解决方案有点不知所措,所以每一次完全不同的尝试也很受欢迎。 xsl:choose 方法的更好解决方案也很酷,它的风格让我毛骨悚然...... 重要的是,我想排除所有不符合规范的内容,并将其放在其他地方。但是,如果没有什么超出规范,什么都不应该发生,除了我改变 a-e 我想在 xsl:choose 中连接变量,并且仅在整个变量不为空时才创建输出,但这在 XSL1.0 中似乎是不可能的
希望我能正确解释我的问题。 提前非常感谢!
reineke
【问题讨论】:
-
我不明白你的问题。您想通过名称或内容来选择要传递给输出的元素吗?如果按名称,您是否有要传递的元素名称白名单或要禁止的元素名称黑名单?
标签: xml xslt foreach xsl-choose