Your support for our advertisers helps cover the cost of hosting, research, and maintenance of this FAQ

The XML FAQ — Frequently-Asked Questions about the Extensible Markup Language

Section 4: Developers

Q 4.22: How can I include a conditional statement in my XML?

You can't, as such: XML isn't a programming language.

You can't as such: XML isn't a programming language, so you can't say things like

<foo if{DB}="A">bar</foo> 

But you can have conditional criteria in a Schema, DTD, or a processor, and some DTDs provide attributes for conditional processing.

If you need to make an element optional, based on some internal or external criteria, you can do so in a Schema. DTDs have no internal referential mechanism, so it isn't possible to express this kind of conditionality in a DTD at the individual element level.

It is possible to express presence-or-absence conditionality in a DTD for the whole document, by using Parameter Entities as Boolean switches to include or ignore certain sections of the DTD based on settings either hardwired in the DTD or supplied in the internal subset. Both the TEI and Docbook DTDs have used this mechanism to implement modularity.

Alternatively you can make the element entirely optional in the DTD or Schema, and provide code in your processing software that checks for its presence or absence. This defers the checking until the processing stage: one of the reasons for Schemas is to provide this kind of checking at the time of document creation or editing.

In processing languages such as XSLT, there are constructs for conditional processing, both for simple IFs and for exclusive case-by-case choices:

<xsl:if test="@foo='bar'">
  <xsl:text>Hello, world!</xsl:text>

  <xsl:when test="$type=1">
    <xsl:apply-templates select="//*[@class='special']"/>
  <xsl:when test="$type=2">
    <xsl:apply-templates select="/foo/bar"/>

DocBook and many other DTDs and Schemas provide attributes on some elements for the specification of effectivities, saying which parts of the document apply in which circumstances. Processing software can then isolate these and process them accordingly.