在XSLT 2.0中使用contains()匹配和过滤节点

时间:2014-01-22 12:37:44

标签: xml xslt xpath xslt-2.0 xpath-2.0

我有一组关于人的XML记录,这些记录编码与其他人的关系,以及相关资源(书籍等)。基本结构是这样的:

<record>
    <name>Smith, Jane</name>
    <relations>
        <relation>Frost, Robert, 1874-1963</relation>
        <relation>Jones, William</relation>            
        <resource>
            <title>Poems</title>
            <author>Frost, Robert</author>
        </resource>
        <resource>
            <title>Some Title</title>
            <author>Author, Some</author>
        </resource>
    </relations>
</record>

我需要在“拉”式XSLT 2.0样式表中处理这个问题 - 这样我就可以过滤掉<relation>个包含或开头的<author>个节点{{1} }节点。这两个不是完全匹配,因为<relation>节点包含其他文本,通常是出生日期和死亡日期。

我最初的冲动是尝试使用一对xsl:for-each循环来测试节点值,但这不起作用。这个样本样式表......

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
    <xsl:template match="/">
        <test>
            <xsl:for-each select="record/relations/relation">
                <xsl:variable name="relation" select="."/>
                <xsl:for-each select="../resource/author">
                    <xsl:variable name="resource" select="."/>
                    <relation>
                        <xsl:value-of select="$relation[not(contains(.,$resource))]"/>
                    </relation>
                </xsl:for-each>
            </xsl:for-each>
        </test>
    </xsl:template>
</xsl:stylesheet>

...给我:

<test>
    <relation/>
    <relation>Frost, Robert, 1874-1963</relation>
    <relation>Jones, William</relation>
    <relation>Jones, William</relation>
</test>

但我真正想要的只是:

<test>
    <relation>Jones, William</relation>
</test>

如何比较这两个节点集并仅筛选出匹配的节点?同样,我需要在现有的“拉”式样式表中执行此操作,该样式表只有一个xsl:template,与文档根相匹配。提前谢谢!

1 个答案:

答案 0 :(得分:2)

我认为你可以在单个XPath 2.0 "quantified expression"中完成此操作,基本上你正在寻找所有relation元素,以便

not(some $author in following::author satisfies contains(., $author))

如果您想在每个../resource/author块中保留支票,则可以使用following::author代替relations

XSLT示例:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes" />

  <xsl:template match="/">
    <test>
      <xsl:sequence select="record/relations/relation[
       not(some $author in following::author satisfies contains(., $author))]" />
    </test>
  </xsl:template>

</xsl:stylesheet>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<test>
   <relation>Jones, William</relation>
</test>
相关问题