I have two xml files: one is the actual data and the second has a list of keys I’d for the nodes I’d like to extract from the data and after much searching and testing I thought I’d ask for help since I’m not getting my desired results.
Data File:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
<ItemKey>12345</ItemKey>
<Name>Apple></Name>
<Attribute>Red</Attribute>
</Item>
<Item>
<ItemKey>67890</ItemKey>
<Name>Orange</Name>
<Attribute>Orange</Attribute>
</Item>
<Item>
<ItemKey>12346</ItemKey>
<Name>Grape</Name>
<Attribute>Purple</Attribute>
</Item>
<Item>
<ItemKey>67891</ItemKey>
<Name>Pear</Name>
<Attribute>Yellow</Attribute>
</Item>
</Items>
Filter File:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
<ItemKey>12345</ItemKey>
</Item>
<Item>
<ItemKey>12346</ItemKey>
</Item>
</Items>
I am trying to transform the data file and extract only the and subnodes that match the ItemKey in the filter file. I’ve tried using several of the examples I’ve seen and used the following xml with no success:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="filter" select="document('Filter.xml')/Item/*"/>
<xsl:template match="/">
<xsl:for-each select="Items/Item">
<xsl:choose>
<xsl:when test="$filter/Item/ItemKey[contains(., ./ItemKey)]">
<xsl:call-template name="Filtered"/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:template>
<xsl:template name="Filtered">
<xsl:text>	"</xsl:text>
<xsl:value-of select="ItemKey" />, <xsl:value-of select="Name"/>
<xsl:text>",
</xsl:text>
</xsl:template>
</xsl:stylesheet>
As you can see I wish to convert to text and will format appropriately once I know I am getting the nodes I’m after. Thanks for any help you can offer.
As simple as this:
When this transformation is applied on the provided source XML document:
and the provided “filter xml” is in the file: c:\temp\delete\filter.xml:
the wanted, correct result is produced:
Explanation:
Proper use of the standard XSLT function
document().