设置空节点的默认值

时间:2010-05-07 19:48:23

标签: xml xslt default

我需要转换一段XML,以便我指定的列表中每个节点的值都设置为“0”

例如:

<contract>
 <customerName>foo</customerName>
 <contractID />
 <customerID>912</customerID>
 <countryCode/>
 <cityCode>7823</cityCode>
</contract>

将转化为

<contract>
 <customerName>foo</customerName>
 <contractID>0</contractID>
 <customerID>912</customerID>
 <countryCode>0</contractID>
 <cityCode>7823</cityCode>
</contract>

如何使用XSLT实现这一目标? 我已经尝试了一些我发现但没有按预期工作的例子

谢谢

1 个答案:

答案 0 :(得分:2)

此转化:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*[not(node())]">
  <xsl:copy>0</xsl:copy>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<contract>
 <customerName>foo</customerName>
 <contractID />
 <customerID>912</customerID>
 <countryCode/>
 <cityCode>7823</cityCode>
</contract>

生成想要的正确结果

<contract>
    <customerName>foo</customerName>
    <contractID>0</contractID>
    <customerID>912</customerID>
    <countryCode>0</countryCode>
    <cityCode>7823</cityCode>
</contract>