【问题标题】:xslt get value from a node based on the value of another nodexslt 根据另一个节点的值从一个节点获取值
【发布时间】:2020-09-03 09:10:57
【问题描述】:

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

这里是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>

到目前为止,我已经找到了这个解决方案 - 创建一个值为 &lt;studentIds&gt; 的变量,然后执行 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>

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

【问题讨论】:

    标签: xml xslt-1.0


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在下面使用:

      <?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查看转换

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-28
        • 1970-01-01
        • 2016-10-11
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        相关资源
        最近更新 更多