Set a Default value for each empty XML tags in XSLT 1.0

心不动则不痛 提交于 2019-12-24 01:57:12

问题


I need to write a default text or number to an empty XML tag using XSLT 1.0, then upon searching here in StackOverflow I happen to look at the solution of Dimitre in this post

What I need is for example I have a tag like below:

<Number></Number> <!--Which is empty--> 

or

<Text></Text> <!--Which is also empty-->

What I need is to put a Default value for each empty tags in my XML like <Number>0.00</Number> for numeric tags and <Text>nil</Text> for Alphanumeric tags, I have quite a big XML so is there any way to make it like an identity template where it will always be read from my input then transform it to Insert the default on empty strings or I can only do the code like below on each field/tags?

<xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>

Thanks in advance.


回答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:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Number[not(node())]">
    <Number>0.00</Number>
  </xsl:template>

  <xsl:template match="Text[not(node())]">
    <Text>nill</Text>
  </xsl:template>
</xsl:stylesheet>

when applied on this XML document (as none was provided):

<t>
  <Number>10</Number>
  <Number/>
  <Text>Hello</Text>
  <Text/>
</t>

produces the wanted, correct result:

<t>
   <Number>10</Number>
   <Number>0.00</Number>
   <Text>Hello</Text>
   <Text>nill</Text>
</t>

Note:

In order to get the systematic knowledge to solve basic problems like this, I (shamelessly) recommend to watch this Pluralsight training course:

XSLT 2.0 and 1.0 Foundations



来源:https://stackoverflow.com/questions/38150093/set-a-default-value-for-each-empty-xml-tags-in-xslt-1-0

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