【发布时间】:2010-02-18 10:11:37
【问题描述】:
我正在使用 XSLT 将 XML 转换为 XML,目的是读取标签 <node1> 的值,如果它为空,则必须为其分配 <node2> 的值,如果是 <node2>,也是null,则必须将默认文本“Default”分配给两个标签..
编辑: 如果 <node2> 为 null 且 <node1> 不是 .. 那么代码不应使用 'Default' 文本更新 <node2>,但必须对其进行转换是..
这是我正在尝试的测试 XML:
<root>
<node1></node1>
<node2></node2>
<parent>
<node1>data1</node1>
<node2></node2>
</parent>
<parent>
<node1></node1>
<node2>data2</node2>
</parent>
<parent>
<node1>data1</node1>
<node2>data2</node2>
</parent>
</root>
这是我设计的 XSLT 代码:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="template1" match="node2[(following-sibling::node1[.='']|preceding-sibling::node1[.=''])]">
<xsl:choose>
<xsl:when test=".=''">
<node1><xsl:text>Default</xsl:text></node1>
<node2><xsl:text>Default</xsl:text></node2>
</xsl:when>
<xsl:otherwise>
<node1>
<xsl:value-of select="text()"/>
</node1>
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="template2" match="node1[.='']"/>
虽然我的代码有效,但我对代码的庞大性不满意.. 有没有办法摆脱多余的(如果有的话)行.. 有没有其他方法可以使用 2 个模板来完成这个(即template1和template2),是否可以减少模板的数量?
【问题讨论】:
-
我个人喜欢 Tomalak 的 sol .. 它满足了很多要求 .. 它看起来很酷,而且技术含量很高 .. 我可以为我的要求编写代码(可能不是 100% 有效的)但是他的代码值得.. 所以被接受.. ;-)
-
我也发布了自己的答案..这将满足需求..
-
我有一个答案,可能值得你关注:)
-
@Dimitre,我已经接受了你的回答..
-
不客气——到目前为止,您一直在发布非常有趣的问题