代码之家  ›  专栏  ›  技术社区  ›  Sandeep

XSLT代码,用于根据条件提取元素值

  •  0
  • Sandeep  · 技术社区  · 5 月前

    我有下面的XML,我想使用XSLT提取p1值为Orange的p2元素值,然后在variablePrint标记中显示该值。

    <rootyFruity xmlns:h="http://www.w3.org/TR/html4/">
    <h:fruit>
        <h:p1>Apple</h:p1>
        <h:p2>1</h:p2>
    </h:fruit>
    <h:fruit>
        <h:p1>Orange</h:p1>
        <h:p2>2</h:p2>
    </h:fruit>
    <h:fruit>
        <h:p1>Guava</h:p1>
        <h:p2>3</h:p2>
    </h:fruit>
    <h:fruit>
        <h:p1>Grapes</h:p1>
        <h:p2>4</h:p2>
    </h:fruit>
    <h:variablePrint>ssss</h:variablePrint>
    </rootyFruity>
    

    下面是XSLT,我可以在其中抓取variablePrint元素,并使用变量在其中显示值5。

    当p1值为橙色时,是否有方法提取p2元素值?

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:miscHelper="http://www.jclark.com/xt/java/glog.webserver.util.MiscellaneousHelper"
                    version="1.0">
    <xsl:variable name="variableName" select="5"/>
        <xsl:output method="xml"/>
        <xsl:template match="node()|@*">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:template> 
        <xsl:template match="//*[local-name()='variablePrint']/text()"> 
            <xsl:value-of select="$variableName"/>
        </xsl:template>
    
    </xsl:stylesheet>
    
    1 回复  |  直到 5 月前
        1
  •  1
  •   Tony Stevens    5 月前

    您可以这样设置变量:

    <xsl:variable name="variableName" select="//h:fruit[h:p1='Orange']/h:p2"/>
    

    这将找到匹配的fruit元素并返回其p2子元素的内容。 您需要添加h:namespace前缀的定义。