XSLT 1.0使用过滤器XML密钥过滤数据XML

时间:2013-01-13 17:25:02

标签: xml xslt xslt-1.0

我有两个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>

正如你所看到的,我希望转换为文本,并且一旦我知道我正在获取我正在追求的节点,就会格式化。感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分: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()