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

时间:2020-09-03 09:10:57

标签: xml xslt-1.0

如何显示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>

但是我相信必须有比这更好的解决方案。

2 个答案:

答案 0 :(得分:2)

使用 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>

答案 1 :(得分:0)

在下面使用:

<?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

相关问题