tosspot
tosspot

Reputation: 165

XSLT 1.0 add element with attribute if it doesn't exist

How can I add an element with attribute if it doesn't exist in the xml file. I would like to add

<c name="EX1">testing</c>

to each "m" node if it does not exist

<?xml version="1.0" encoding="UTF-8"?>
<h>
  <m>
    <c name="HM">G</c>
    <c name="HL">20</c>
    <c name="HS">f</c>
  </m>
  <m>
    <c name="HM">L</c>
    <c name="HL">30</c>
    <c name="HS">t</c>
  </m>
  <m>
    <c name="HM">S</c>
    <c name="HL">10</c>
    <c name="HS">t</c>
    <c name="EX1">testing</c>
  </m>
</h>

Here is my xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Here is my desired output

 <?xml version="1.0" encoding="UTF-8"?>
    <h>
      <m>
        <c name="HM">G</c>
        <c name="HL">20</c>
        <c name="HS">f</c>
        <c name="EX1">testing</c>
      </m>
      <m>
        <c name="HM">L</c>
        <c name="HL">30</c>
        <c name="HS">t</c>
        <c name="EX1">testing</c>
      </m>
      <m>
        <c name="HM">S</c>
        <c name="HL">10</c>
        <c name="HS">t</c>
        <c name="EX1">testing</c>
      </m>
    </h>

Upvotes: 2

Views: 1145

Answers (1)

Tim C
Tim C

Reputation: 70648

With the identity template being used, all you need to do is add a second template matching m elements (I am assuming you meant m not h here) where the required node does not exist, like so

<xsl:template match="m[not(c[@name='EX1' and text()='testing'])]">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()" />
    <c name="EX1">testing</c>
  </xsl:copy>
</xsl:template>

Upvotes: 2

Related Questions