Home > other >  Need help on value comparison using XSLT
Need help on value comparison using XSLT

Time:11-24

I have a XML which have two parent nodes (Base, Sub). I need to write a XSLT to get the values for below condition.

Condition: If the value inside Sub contains in Base also XSLT should add that value to the output.

Input XML:

<?xml version="1.0 encoding="UTF-8"?>
<Data>
  <Base>
    <Student_ID>1234</Student_ID>
    <Student_ID>1267</Student_ID>
    <Student_ID>1890</Student_ID>
    <Student_ID>5678</Student_ID>
    <Student_ID>6743</Student_ID>
    <Student_ID>8743</Student_ID>
  </Base>
  <Sub>
    <Student_ID>5678</Student_ID>
    <Student_ID>6743</Student_ID>
    <Student_ID>3226</Student_ID>
    <Student_ID>8123</Student_ID>
  </Sub>
</Data>

Expected Output:

<?xml version="1.0 encoding="UTF-8"?>
<Data>
    <Student_ID>5678</Student_ID>
    <Student_ID>6743</Student_ID>
</Data>

Since I'm new to XSLT need a help on this.

CodePudding user response:

Please try the following.

Input XML

<?xml version="1.0"?>
<Data>
    <Base>
        <Student_ID>1234</Student_ID>
        <Student_ID>1267</Student_ID>
        <Student_ID>1890</Student_ID>
        <Student_ID>5678</Student_ID>
        <Student_ID>6743</Student_ID>
        <Student_ID>8743</Student_ID>
    </Base>
    <Sub>
        <Student_ID>5678</Student_ID>
        <Student_ID>6743</Student_ID>
        <Student_ID>3226</Student_ID>
        <Student_ID>8123</Student_ID>
    </Sub>
</Data>

XSLT 1.0

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

    <xsl:template match="Data">
        <xsl:copy>
            <xsl:for-each select="Sub/Student_ID[. = /Data/Base/Student_ID]">
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output

<?xml version='1.0' encoding='utf-8' ?>
<Data>
  <Student_ID>5678</Student_ID>
  <Student_ID>6743</Student_ID>
</Data>

CodePudding user response:

I strongly recommend using a key to resolve cross-references. In your case it could look like this:

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

<xsl:key name="base" match="Base/Student_ID" use="." />

<xsl:template match="/Data">
    <xsl:copy>
        <xsl:copy-of select="key('base', Sub/Student_ID)"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
  • Related