为空节点设置默认值 [英] setting default values for empty nodes

查看:52
本文介绍了为空节点设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to transform a piece of XML, so that the value of every node in a list I specify is set to "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 实现这一点?我尝试了一些我发现的例子,但没有一个按预期工作

How can this be accomplished using XSLT? I have tried some examples I found but none works as expected

谢谢

推荐答案

这种转变:

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

这篇关于为空节点设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆