2013-01-13 65 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()的。