0

I have the following XML structure

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <BookingGroup>
        <PostCodes>
            <PostCode >AB</PostCode>
            <PostCode >AL</PostCode>
        </PostCodes>
    </BookingGroup>
    <BookingGroup>
        <PostCodes>
            <PostCode >AB</PostCode>
            <PostCode >D</PostCode>
        </PostCodes>
    </BookingGroup>
</Root>

Now for every post code AB in the entire Xml I need the output as:

<Root>
    <Child>
        <Child1>
        </Child1>
        <Child1>
        </Child1>
</root>

because there are two AB postcode I need two child1 elements.

2
  • 1
    The question, as currently phrased, is incomprehensible.
    – jrockway
    Jul 21, 2009 at 13:56
  • 1
    I wonder if people ever read the stuff they write? No-one can actually be so handicapped and work with XML at the same time. But then again, maybe it is possible. xkcd.com/481
    – Tomalak
    Jul 21, 2009 at 14:40

1 Answer 1

1

If you are looking for that literal output, this will do

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

  <xsl:variable name="firstNode" select="//PostCode[1]"/>
  <!-- for a literal value use <xsl:variable name="firstNode">AB</xsl:variable> -->

  <xsl:template match="Root">
    <Root>
      <Child>
    <xsl:apply-templates select="//PostCode"/>
      </Child>
    </Root>
  </xsl:template>

  <xsl:template match="PostCode">
    <xsl:if test=".=$firstNode">
      <Child1>
    <xsl:apply-templates select="@* | node()"/>
      </Child1>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

If you are looking for a general solution that will output whatever nodes are in the input try this

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

  <xsl:variable name="firstNode" select="//PostCode[1]"/>
  <!-- for a literal value use <xsl:variable name="firstNode">AB</xsl:variable> -->

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

  <xsl:template match="PostCode">
    <xsl:if test=".=$firstNode">
      <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.