setting default values for empty nodes

泄露秘密 提交于 2021-01-28 10:22:42

问题


I need to transform a piece of XML, so that the value of every node in a list I specify is set to "0"

for example:

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

would be transformed into

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

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

Thank you


回答1:


This transformation:

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

when applied on the provided XML document:

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

produces the wanted, correct result:

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


来源:https://stackoverflow.com/questions/2791295/setting-default-values-for-empty-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!