使用XSLT 3.0转换XML 如何根据同级元素值选择元素进行输出?

问题描述 投票:0回答:1

我有一个XML输入,如下图所示。我想打印Cust_1, Gender & Price字段的每个客户信息的输出。我只想打印红色的椅子的价格。我试过使用choose-when和if,但没有得到想要的输出。任何帮助是非常感激的。

<Sales_Data>
    <Furniture>
        <Customer_Reference>Cust_1</Customer_Reference>
        <Gender>M</Gender>
        <Chairs>
            <Color_Ref>Black</Color_Ref>
            <Price>
                <Unit_Price>1000</Unit_Price>
            </Price>
        </Chairs>
        <Chairs>
            <Color_Ref>Red</Color_Ref>
            <Price>
                <Unit_Price>1100</Unit_Price>
            </Price>
        </Chairs>
    </Furniture>
    <Furniture>
        <Customer_Reference>Cust_2</Customer_Reference>
        <Gender>F</Gender>
        <Chairs>
            <Color_Ref>Blue</Color_Ref>
            <Price>
                <Unit_Price>950</Unit_Price>
            </Price>
        </Chairs>
        <Chairs>
            <Color_Ref>Red</Color_Ref>
            <Price>
                <Unit_Price>1050</Unit_Price>
            </Price>
        </Chairs>
    </Furniture>
</Sales_Data>
xml xslt-3.0
1个回答
1
投票

要输出所需的值,请使用以下XPath-1.0表达式。

/Sales_Data/Furniture[Customer_Reference='Cust_1' and Gender='M']/Chairs[Color_Ref='Red']/Price/Unit_Price

或完整的XSLT样式表

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />

    <xsl:template match="/">
      <xsl:value-of select="/Sales_Data/Furniture[Customer_Reference='Cust_1' and Gender='M']/Chairs[Color_Ref='Red']/Price/Unit_Price"/>
    </xsl:template>

</xsl:stylesheet>

在这两种情况下,输出都是期望值 1100.

© www.soinside.com 2019 - 2024. All rights reserved.