XSLT仅显示与id匹配的一行

时间:2017-11-02 15:37:47

标签: xml xslt select

我目前正在努力改造我的XML以满足我的需求。 XML代码如下:

<stk:stockPriceItem>
<stk:stockPrice>
<typ:id>11</typ:id>
<typ:ids>sleva 3%</typ:ids>
<typ:price>743.6</typ:price>
</stk:stockPrice>
<stk:stockPrice>
<typ:id>9</typ:id>
<typ:ids>V.I.P. 0%</typ:ids>
<typ:price>613.3</typ:price>
</stk:stockPrice>
<stk:stockPrice>
<typ:id>4</typ:id>
<typ:ids>Velko 5%</typ:ids>
<typ:price>552</typ:price>
</stk:stockPrice>
<stk:stockPrice>
<typ:id>12</typ:id>
<typ:ids>eshop</typ:ids>
<typ:price>651.6</typ:price>
</stk:stockPrice>
<stk:stockPrice>
<typ:id>5</typ:id>
<typ:ids>Malo 10%</typ:ids>
<typ:price>582.6</typ:price>
</stk:stockPrice>
<stk:stockPrice>
<typ:id>1</typ:id>
<typ:ids>Prodejní</typ:ids>
<typ:price>766.6</typ:price>
</stk:stockPrice>
</stk:stockPriceItem>

我需要输出,当我新的转换后的XML只显示typ:price for typ:id = 12。

如下:

<stk:stockPrice>
 <typ:price>1222</typ:price>
</stk:stockPrice>

任何帮助都会非常感激,因为我无法在线找到解决方案,而且我在使用XSLT时非常新手。 非常感谢你。

2 个答案:

答案 0 :(得分: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"
    xmlns:stk="urn:stk" xmlns:typ="urn:typ"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="stk:stockPriceItem">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="stk:stockPrice[string(typ:id) eq '12']" priority="5">
        <xsl:copy>
            <xsl:copy-of select="typ:price"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="node()"/>

</xsl:stylesheet>

[输出]

<?xml version="1.0" encoding="UTF-8"?>
<stk:stockPrice xmlns:stk="urn:stk" xmlns:typ="urn:typ">
   <typ:price>651.6</typ:price>
</stk:stockPrice>

请注意,名称空间声明是临时的,因为您没有在输入XML文件中指定它们。

答案 1 :(得分:0)

我设法用这个解决了问题的解决方法。

<xsl:value-of select="stk:stockPrice[typ:id=12]/typ:price"/>

感谢您的帮助。