我不确定标题是否正确。我有一个如下所示的 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>
我格式化文件以适应某种规范。标签 ae 都是已知和想要的。但是也有可能里面还有其他不符合规范的东西。(即基本的,随机的和东西)。我写了以下
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>
这几乎可以实现我想要实现的目标。问题是,我不知道除了规范之外是否还有任何东西,如果上面没有基本、随机或东西之类的东西,那么根本就不应该有 < undefined > 标签。输出是
输出
<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 方法的更好解决方案也很酷,它的风格让我毛骨悚然……重要的是,我想排除所有不符合规范的内容,并将其放在其他地方。但是,如果除了规范之外什么都没有,什么都不应该发生,除了我改变 ae 我想在 xsl:choose 中连接变量,并且只有在整个变量不为空时才创建输出,但这在 XSL1 中似乎是不可能的.0
希望我能正确解释我的问题。提前非常感谢!
雷内克