Anchal Sarraf
Anchal Sarraf

Reputation: 3919

How to extract specific value from XML either using Xpath or XSLT

I need to extract value for each AvamarGrid on the basis of Day.

  <AvamarGridTime Day="Monday">
    <AvamarGrid>frk-opavautl921</AvamarGrid>
  </AvamarGridTime>
  <AvamarGridTime Day="Tuesday">
    <AvamarGrid>ftc-opavautl961</AvamarGrid>
    <AvamarGrid>ftc-opavbutl921</AvamarGrid>
    <AvamarGrid>ptc-opavautl981</AvamarGrid>
  </AvamarGridTime>
  <AvamarGridTime Day="Wednesday">
    <AvamarGrid>lhr-opavautl941</AvamarGrid>
  </AvamarGridTime>
a
  <AvamarGridTime Day="Thursday">
    <AvamarGrid>sf1-its-bku-t01</AvamarGrid>
    <AvamarGrid>sf1-opavautl901</AvamarGrid>
  </AvamarGridTime>
  <AvamarGridTime Day="Friday">
    <AvamarGrid>par-opavautl921</AvamarGrid>
  </AvamarGridTime>
</AvamarGrids>

I am using below XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output indent="no" />
  <xsl:template match="/">
    <Day>
      <xsl:for-each select="//AvamarGridTime">
        <xsl:if test="//AvamarGridTime[@Day=&quot;Monday&quot;]">
          <xsl:value-of select="AvamarGrid" disable-output-escaping="no" />
        </xsl:if>
      </xsl:for-each>
    </Day>
  </xsl:template>
</xsl:stylesheet>

But, getting below output, instead of just : frk-opavautl921

<?xml version="1.0" encoding="UTF-8"?><Day>frk-opavautl921ftc-opavautl961lhr-opavautl941sf1-its-bku-t01par-opavautl921</Day>

Upvotes: 0

Views: 245

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117175

Your test:

<xsl:if test="//AvamarGridTime[@Day=&quot;Monday&quot;]">

checks the existence of a AvamarGridTime element whose Day attribute is Monday in the entire XML input. This returns true for every one of the checked nodes. To test only the current node, change it to:

<xsl:if test="@Day=&quot;Monday&quot;">

Or do simply:

<xsl:template match="/AvamarGrids">
    <Day>
        <xsl:value-of select="AvamarGridTime[@Day='Monday']/AvamarGrid" />
    </Day>
</xsl:template>

Added:

In order to create a separate Day element for each AvamarGrid within the selected AvamarGridTime, you can do:

<xsl:template match="/AvamarGrids">
    <xsl:for-each select="AvamarGridTime[@Day='Tuesday']/AvamarGrid">
        <Day>
            <xsl:value-of select="." />
        </Day>
    </xsl:for-each>
</xsl:template>

However, do note that the result is an XML fragment. If you want to produce a well-formed XML document, you must add a root element.

Upvotes: 1

Related Questions