xslt 根据另一个节点的值从一个节点获取值

xslt get value from a node based on the value of another node

如何显示 students/student/name 节点中存在的 <studentIds>

这里是xml节点引用-

<?xml version="1.0" encoding="UTF-8"?>

<test>
    <studentIds>
        <id><![CDATA[123]]></id>
        <id><![CDATA[126]]></id>
    </studentIds>

    <students>
        <student>
            <id><![CDATA[123]]></id>            
            <name><![CDATA[Goku]]></name>
        </student>

        <student>
            <id><![CDATA[124]]></id>            
            <name><![CDATA[Luffy]]></name>
        </student>

        <student>
            <id><![CDATA[126]]></id>            
            <name><![CDATA[Naruto]]></name>
        </student>
    </students>
</test>

到目前为止,我已经找到了这个解决方案 - 创建一个值为 <studentIds> 的变量,然后执行 contains() -

<xsl:variable name="sid">
    <xsl:for-each select="test/studentIds/value">
        <xsl:value-of select="."/>
        <xsl:if test="position() != last()">&#160;</xsl:if>
    </xsl:for-each>
</xsl:variable>
 
<xsl:for-each select="test/students/student">
    <xsl:if test="contains($sid, id)">
       <xsl:apply-templates select="name"/>&#160;
    </xsl:if>
</xsl:for-each>

但我相信一定有比这个更好的解决方案。

使用 key:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:key name="stu" match="student" use="id" />

<xsl:template match="/test">
    <xsl:for-each select="studentIds/id">
        <xsl:value-of select="key('stu', .)/name"/>
        <xsl:if test="position() != last()">&#160;</xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

使用如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="1.0">
    
    <xsl:key name="studentname" match="student" use="id"/>

    <xsl:template match="/">
        <studentIds>
            <xsl:for-each select="//studentIds/id">
                <xsl:copy-of select="."/>
                <xsl:copy-of select="//key('studentname', current())/name"/>
            </xsl:for-each>
        </studentIds>
    </xsl:template>
    
    
</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/naZYrqc

查看转换