XSLT通过将元素文本与子串结果进行比较来查找匹配节点

时间:2011-08-11 17:38:25

标签: string xslt comparison

我正在处理这个XML:

<Brand>
<Brand_Name>BLENDERM</Brand_Name>
<Brand_Code>1103</Brand_Code>
<Groups>
<Group>
<Group_Code>657</Group_Code>
<Parent_Code>0</Parent_Code>
<Group_Level>1</Group_Level>
<Group_Name>Brand Default</Group_Name>
<Product>
<Pip_code>0032359</Pip_code>
<Status>In Use</Status>

使用此XSLT:

<xsl:template match="Product" mode="phase-3">
<xsl:value-of select="document('rx_catmapping.xml')/descendant::mapping[source=substring(ancestor::Brand/Brand_Name,1,1)]/target"/>
</xsl:template>

以下是rx_catmapping.xml的示例:

<Lookup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <mapping>
        <source>a</source>
        <target>788</target>
    </mapping>
    <mapping>
        <source>B</source>
        <target>789</target>
    </mapping>
</Lookup>

所以,我正在处理Product元素,它是Brand的后代。在这种情况下,Brand/Brand_Name的第一个字母是B,我试图通过在rx_catmapping.xml中查找来输出值789。这应该很简单,但我完全难过!我尝试更改XPath的第一部分以引用document('rx_catmapping.xml')/Lookup/mappingdocument('rx_catmapping.xml')//mapping。我也尝试将比较的前半部分更改为string(source)或更改为source/text(),但这些都不起作用。 (尝试这个的原因是,例如,使用source='B'似乎确实有用,所以我想知道我是否在尝试比较两种不兼容的数据类型。)

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

定义一个键

<xsl:key name="k1" match="mapping" use="source"/>

然后使用

<xsl:variable name="map-doc" select="document('rx_catmapping.xml')"/>

<xsl:variable name="letter" select="substring(ancestor::Brand/Brand_Name,1,1)"/>
<xsl:for-each select="$map-doc">
  <xsl:value-of select="key('k1', $letter)/target"/>
</xsl:for-each>

使用XSLT 2.0,您可以将其简化为

<xsl:value-of select="key('k1', substring(ancestor::Brand/Brand_Name,1,1), $map-doc)"/>

答案 1 :(得分:-1)

问题是,我相信,在您执行ancestor::Brand/Brand_Name时,上下文是外部文件中的mapping元素。这对我有用

  <xsl:template match="/">
    <xsl:apply-templates select=".//Product"/>
  </xsl:template>
  <xsl:template match="Product">
    <xsl:variable name="x" select="substring(ancestor::Brand/Brand_Name,1,1)"/>
      <xsl:value-of select="document('file:///c:/temp/rx_catmapping.xml')//mapping[source=$x]/target"/>
  </xsl:template>