在 XSLT 中使用 AND 条件交叉引用

Cross-referencing with AND condition in XSLT

我正在尝试从外部 XML 文件进行交叉引用,但我不想只比较一个键,而是想询问一个字符串和其他字符串是否存在,如果存在,则来自外部文件的引用:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:t="http://www.tei- 
c.org/ns/1.0"
xmlns="http://www.tei-c.org/ns/1.0" exclude-result-prefixes="xs t">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="ids"
    select="document('instructions.xml')"/>

<xsl:key name="id" match="row" use="tokenize(normalize-space(elem[@name='Instruction']), ' ')"/>


<!-- identity transform -->
<xsl:template match="@* | node() | text() | *">
    <xsl:copy>
        <xsl:apply-templates select="@* | node() | text() | *"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="instruction">
    <xsl:for-each select=".[contains(.,key('id', ., .))]">
    <xsl:copy>     
        <xsl:attribute name="norm">
            <xsl:value-of select="normalize-space(key('id', normalize-space(.), $ids)/elem[@name='Norm'])"/>
        </xsl:attribute>
        <xsl:apply-templates select="@* | node() | text() | *"/>   
    </xsl:copy>
    </xsl:for-each>
</xsl:template>

输入(外部文件):

<row>
  <elem name="instruction">pour out</elem>
  <elem name="norm">p1</elem>
</row>

输入(要注释的文件):

<ab type="recipe">
Bla bla
  <instruction>pour the milk out</instruction> bla
</ab>

期望的输出:

<ab type="recipe">
Bla bla
  <instruction norm="p1">pour the milk out</instruction> bla
</ab>

换句话说:元素 <elem name="instruction"> "pour" 和 "out" 中的外部 XML 文件中的两个标记都需要包含在 <instruction> 我的 XML 文件中的元素。如果是,我想在外部文件中将 norm 属性设置为 <elem name="norm"> 的值。

非常感谢任何帮助!

我不知道如何用钥匙来做,但我确实想出了一个替代方法....

<xsl:template match="instruction">
    <xsl:variable name="words" select="tokenize(normalize-space(.), ' ')" />
    <xsl:variable name="row" select="$ids//row[every $i in tokenize(normalize-space(elem[@name='instruction']), ' ') satisfies $i = $words]" />
    <xsl:copy>
        <xsl:if test="$row">
            <xsl:attribute name="norm" select="$row/elem[@name='norm']" />    
        </xsl:if>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

编辑:针对您的评论,如果您可以匹配多行,那么要获得匹配词最多的行,请执行此操作....

<xsl:template match="instruction">
    <xsl:variable name="words" select="tokenize(normalize-space(.), ' ')" />
    <xsl:variable name="row" as="element()*">
        <xsl:perform-sort select="$ids//row[every $i in tokenize(normalize-space(elem[@name='instruction']), ' ') satisfies $i = $words]">
            <xsl:sort select="count(tokenize(normalize-space(elem[@name='instruction']), ' '))" order="descending" />
        </xsl:perform-sort>
    </xsl:variable>
    <xsl:copy>
        <xsl:if test="$row">
            <xsl:attribute name="norm" select="$row[1]/elem[@name='norm']" />    
        </xsl:if>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>