【问题标题】:setting default values for empty nodes为空节点设置默认值
【发布时间】:2010-05-07 19:48:23
【问题描述】:

我需要转换一段 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)。请参阅我的答案以获得完整的解决方案。 :)

标签: xml xslt default


【解决方案1】:

这种转变:

<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>

【讨论】:

  • 你是 XSLT 大师,Dimitre。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2015-10-02
相关资源
最近更新 更多