Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop processing XML when certain node is reached

Tags:

xml

xslt

xpath

I am creating a form from XML. I have the following XML:

<data>
  <personal-info type="legend" label="Personal Info"/>
  <first-name type="field" label="First Name"/>
  <last-name type="field" label="Last Name"/>
  <settings-info type="legend" label="Settings Info"/>
  <timezone type="field" label="Timezone"/>
</data>

@type attributes that equal legend indicate where a new fieldset should be created. The problem I'm having is that I cannot get the first fieldset to stop processing the XML when it reaches the next node with @type equal to legend. Here is the result I want to create:

<fieldset>
    <legend>Personal Info</legend>
  <label>First Name</label>
  <input type="text" name="first-name" />
  <label>Last Name</label>
  <input type="text" name="last-name" />
</fieldset>
<fieldset>
    <legend>Settings Info</legend>
  <label>TimeZone</label>
  <input type="text" name="timezone" />
</fieldset>

Is this possible using the current XML structure (I can't change it)?

like image 243
Mark Lewis Avatar asked Sep 28 '26 01:09

Mark Lewis


1 Answers

Here is a sample XSLT:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:key name="k1" match="data/*[not(@type = 'legend')]" use="generate-id(preceding-sibling::*[@type = 'legend'][1])"/>

  <xsl:template match="data">
    <xsl:apply-templates select="*[@type = 'legend']"/>
  </xsl:template>

  <xsl:template match="data/*[@type = 'legend']">
    <fieldset>
      <legend>
        <xsl:value-of select="@label"/>
      </legend>
      <xsl:apply-templates select="key('k1', generate-id())"/>
    </fieldset>
  </xsl:template>

  <xsl:template match="data/*[@type = 'field']">
    <label>
      <xsl:value-of select="@label"/>
    </label>
    <input type="text" name="{local-name()}"/>
  </xsl:template>

</xsl:stylesheet>
like image 89
Martin Honnen Avatar answered Sep 29 '26 19:09

Martin Honnen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!