如何根据xslt中的多个条件从多个节点中选择数据?

时间:2015-11-26 20:27:52

标签: xml xslt xpath

我想显示红色部件和供应商ID为1的部件。如何在xslt中实现此目的?

我尝试过使用xpath,但我只能得到像sid = 1和color = red但不是两者的值!

<table>
    <suppliers>
        <supply>
            <sid>1</sid>
            <sname> vishal</sname>
            <address> wtf lane</address>

        </supply>

        <supply>
            <sid>2</sid>
            <sname> vishal</sname>
            <address> wtf lane</address>

        </supply>



    </suppliers>

    <parts>
        <part>
            <pid>1</pid>
            <pname>kacha</pname>
            <color>red</color>
        </part>

    </parts>

    <catalogs>
        <catalog>
            <sid>1</sid>
            <pid>1</pid>
            <cost> 5 rs</cost>
        </catalog>

    </catalogs>

</table>

1 个答案:

答案 0 :(得分:1)

  

我想显示红色部件和供应商ID为1的部件。

你的问题并不完全清楚。以下样式表选择catalogsid1的{​​{1}}条目,而part color对应{&#34;红色&#34;

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="part" match="part" use="pid" />
<xsl:key name="supplier" match="supply" use="sid" />

<xsl:template match="/table">
    <items>
        <xsl:for-each select="catalogs/catalog[sid=1 and key('part', pid)/color='red']">
            <item>
                <xsl:copy-of select="key('part', pid)/pname"/>
                <xsl:copy-of select="key('supplier', sid)/sname"/>
                <xsl:copy-of select="cost"/>
            </item>
        </xsl:for-each>
    </items>
</xsl:template>

</xsl:stylesheet> 

测试输入

<table>
   <suppliers>
      <supply>
         <sid>1</sid>
         <sname>supplier A</sname>
         <address>address A</address>
      </supply>
      <supply>
         <sid>2</sid>
         <sname>supplier B</sname>
         <address>address B</address>
      </supply>
   </suppliers>
   <parts>
      <part>
         <pid>1</pid>
         <pname>part A</pname>
         <color>red</color>
      </part>
      <part>
         <pid>2</pid>
         <pname>part B</pname>
         <color>blue</color>
      </part>
   </parts>
   <catalogs>
      <catalog>
         <sid>1</sid>
         <pid>1</pid>
         <cost>101</cost>
      </catalog>
      <catalog>
         <sid>1</sid>
         <pid>2</pid>
         <cost>102</cost>
      </catalog>
      <catalog>
         <sid>2</sid>
         <pid>1</pid>
         <cost>103</cost>
      </catalog>
     <catalog>
         <sid>2</sid>
         <pid>2</pid>
         <cost>104</cost>
      </catalog>
   </catalogs>
</table>

<强>结果

<?xml version="1.0" encoding="UTF-8"?>
<items>
   <item>
      <pname>part A</pname>
      <sname>supplier A</sname>
      <cost>101</cost>
   </item>
</items>