2013-01-13 63 views
2

我有两个XML文件:一个是实际数据,第二个有一个键的列表我想要从数据中提取的节点和经过大量搜索和测试我想我会寻求帮助,因为我没有得到我想要的结果。XSLT 1.0过滤数据XML与过滤器XML密钥

数据文件:

<?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> 

过滤器文件:

<?xml version="1.0" encoding="UTF-8"?> 
<Items> 
    <Item> 
    <ItemKey>12345</ItemKey> 
    </Item> 
    <Item> 
    <ItemKey>12346</ItemKey> 
    </Item> 
</Items> 

我想转换成数据文件,并只提取过滤器文件匹配的ItemKey的和子节点。我用几个我见过的例子尝试和使用下面的XML没有成功:

<?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>&#x9;"</xsl:text> 
     <xsl:value-of select="ItemKey" />, <xsl:value-of select="Name"/> 
     <xsl:text>",&#xA;</xsl:text> 
    </xsl:template> 
</xsl:stylesheet> 

正如你可以看到我希望转换成文本,并会相应地格式化一次,我知道我得到我在之后的节点。谢谢你尽你所能的帮助。

回答

0

像这样简单

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="/"> 
    <xsl:copy-of select= 
    "/*/Item[ItemKey = document('file:///c:/temp/delete/filter.xml')/*/*/ItemKey]"/> 
</xsl:template> 
</xsl:stylesheet> 

当这个变换所提供的源XML文档应用:

<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> 

和所提供的 “过滤器的XML” 是在文件:c:\ temp \ delete \ filter.xml:

<Items> 
    <Item> 
    <ItemKey>12345</ItemKey> 
    </Item> 
    <Item> 
    <ItemKey>12346</ItemKey> 
    </Item> 
</Items> 

的想要的,正确的结果产生:

<Item> 
    <ItemKey>12345</ItemKey> 
    <Name>Apple&gt;</Name> 
    <Attribute>Red</Attribute> 
</Item> 
<Item> 
    <ItemKey>12346</ItemKey> 
    <Name>Grape</Name> 
    <Attribute>Purple</Attribute> 
</Item> 

说明

正确使用的标准XSLT函数document()的。