David
David

Reputation: 135

In XSLT, how do you show the value of a child node depending of the value of another child node

I am trying to use XSLT to transform one XML document into another XML document.

The original XML is formatted like so;

<NodeList>
    <Node>
      <Type>Commercial</Type>
      <ContactDetail>
        <Name>The Shop</Name>
        <Line01>1 The Lane</Line01>
        <Line02></Line02>
        <Line03>London</Line03>
        <PostCode>SW11AA</PostCode>
        <TelMobile>07777123456</TelMobile>
      </ContactDetail>
    </Node>
    <Node>
      <Type>Municiple</Type>
      <ContactDetail>
        <Name>Some place</Name>
        <Line01>1 Hub Lane</Line01>
        <Line02>PLYMOUTH</Line02>
        <Line03>DEVON</Line03>
        <Line04></Line04>
        <PostCode>PL62BB<</PostCode>
        <TelMobile>01234567890</TelMobile>
      </ContactDetail>
    </Node>
<NodeList>

And I need to be able to print the contact details of NodeList/Node[Type='Commercial'] but for the life of me, I can not find the correct way of doing this.

I thought something along the lines of;

<xsl:value-of select="NodeList/Node/[Type='Commercial"]/ContactDetails/Name" />

But of course "ContactDetails" isn't a child of "Type".

Can anyone point me in the correct direction?

Upvotes: 0

Views: 53

Answers (3)

StuartLC
StuartLC

Reputation: 107247

If you need to access repeated nodes, you can use xsl:key, for example:

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

   <xsl:key name="nodeTypeKey" match="Node" use="Type" />

   <xsl:template match="/">
      <xsl:variable name="addressToUse" 
                    select="key('nodeTypeKey', 'Commercial')/ContactDetail">
      </xsl:variable>
      <Name><xsl:value-of select="$addressToUse/Name"/></Name>
      <Tel><xsl:value-of select="$addressToUse/TelMobile"/></Tel>
      <!-- etc -->
   </xsl:template>
</xsl:stylesheet>

Upvotes: 0

fire.eagle
fire.eagle

Reputation: 2783

You were on the right track. Remove the slash between Node and your condition. That way you are selecting the Node element that matches the condition in the brackets.

NodeList/Node[Type="Commercial"]/ContactDetail/Name

Also, the condition was checking for 'Commercial", which will give you an error from the quotes, and the end of the xpath was looking for ContactDetails instead of ContactDetail, which is what your example had. Both of those are corrected in the above query.

Upvotes: 2

Martin Honnen
Martin Honnen

Reputation: 167506

The correct syntax is NodeList/Node[Type='Commercial']/ContactDetails/Name.

Upvotes: 2

Related Questions