Reputation: 213
I am completely new to XML so I have no idea how to do this :
Suppose I have the following XML File 1 :
<Items>
<Item>
<name> Item1 </name>
<value> 10 </value>
</Item>
</Items>
and file 2 :
<Items>
<Item>
<name> Item1 </name>
<value> 20 </value>
</Item>
</Items>
How do I compare value field of these 2 items in any way using XSLT ?
Upvotes: 0
Views: 75
Reputation: 338208
You could apply a stylesheet like the following to your first XML and pass in the path of the second XML document as a param
(read the documentation of your XSLT processor on how to pass parameters).
The template will check each <Item>
in XML #1, find the first item with the same <name>
in the other XML ($otherDoc//Item[name = $ownName][1]/value
) and compare their respective <value>
s.
It would then generate text output, one line for each such comparison it makes.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:param name="otherDocPath" select="''" />
<xsl:variable name="otherDoc" select="document($otherDocPath)" />
<xsl:template match="/">
<!-- handle each item in this document -->
<xsl:apply-templates select="/Items/Item" />
</xsl:template>
<xsl:template match="Item">
<xsl:variable name="ownName" select="name" />
<xsl:variable name="ownValue" select="value" />
<xsl:variable name="otherValue" select="$otherDoc//Item[name = $ownName][1]/value" />
<!-- output one line of information per item -->
<xsl:value-of select="concat($ownName, ': ')" />
<xsl:choose>
<xsl:when test="$ownValue = $otherValue">
<xsl:value-of select="concat('same value (', $ownValue, ')')" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat('different (', $ownValue, '/', $otherValue, ')')" />
</xsl:otherwise>
</xsl:choose>
<xsl:text>
</xsl:text><!-- new line -->
</xsl:template>
</xsl:stylesheet>
Beware of spaces around names/values. If your input really looks like <value> 10 </value>
, you want to use normalize-space()
before you compare/output anything (<xsl:variable name="ownValue" select="normalize-space(value)" />
etc.).
Output would look like:
Item1: different (10/20) Item2: same value (20) Item3: different (20/)
where lines 1 and 2 stand for an item that are in both XML documents, line 3 stands for an item that is only in the first.
Of course text output is only one possibility, you could output different formats (XML, HTML).
Upvotes: 1