通过XSLT从XML中选择特定元素

时间:2013-04-03 14:18:49

标签: xml xslt xslt-1.0

我在变量中有这样的XML 的 prdxml

 <root>
  <product>
    <estocklevel>0</estocklevel>
    <id>8142229</id>
    <isp_brand extra="isp_brand"></isp_brand>
    <isp_produktserie extra="isp_produktserie"></isp_produktserie>
    <isp_model extra="isp_model"></isp_model>
  </product>
  <product>
    <estocklevel>0</estocklevel>
    <id>8143793</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Bred</isp_model>
  </product> 
  <product>
    <estocklevel>0</estocklevel>
    <id>8143794</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Smal</isp_model>
  </product>
  <product>
    <id>8143796</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Smal</isp_model>
  </product>
</root>

我想从中选择一个id = 8143794的产品节点,不使用for loop.can任何一个提供任何线索

2 个答案:

答案 0 :(得分:4)

/root/product[id='8143794']

那说“找到/ root /产品”id“元素子”到“product”是8143794“

关于如何在将来的查询中使用变量,有一个答案:XSL: How best to store a node in a variable and then us it in future xpath expressions?

答案 1 :(得分:2)

使用XSLT 1.0,我们确实需要知道名为prdxml的变量的类型是node-set还是result tree fragment

如果是节点集,您只需选择$prdxml/root/product[id = 8143794]即可。但如果您有结果树片段,则首先需要应用exsl:node-set之类的扩展功能,例如exsl:node-set($prdxml)/root/product[id = 8143794]

因此,如果有的话,请检查变量的设置位置和方式。

<xsl:variable name="prdxml" select="document('products.xml')"/>

你有一个节点集,但是有例如。

<xsl:variable name="prdxml">
<root>
  <product>
    <estocklevel>0</estocklevel>
    <id>8142229</id>
    <isp_brand extra="isp_brand"></isp_brand>
    <isp_produktserie extra="isp_produktserie"></isp_produktserie>
    <isp_model extra="isp_model"></isp_model>
  </product>
  <product>
    <estocklevel>0</estocklevel>
    <id>8143793</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Bred</isp_model>
  </product> 
  <product>
    <estocklevel>0</estocklevel>
    <id>8143794</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Smal</isp_model>
  </product>
  <product>
    <id>8143796</id>
    <isp_brand extra="isp_brand">Leitz</isp_brand>
    <isp_produktserie extra="isp_produktserie">180</isp_produktserie>
    <isp_model extra="isp_model">Smal</isp_model>
  </product>
</root>
</xsl:variable>

你有一个结果树片段,需要第二种方法(并支持exsl:node-set或类似):

<xsl:variable name="prod" select="exsl:node-set($prdxml)/root/product[id = 8143794]" xmlns:exsl="http://exslt.org/common"/>