XSLT获取同一标记内多个元素的文本值

时间:2017-04-12 10:36:16

标签: xml xslt

我有这段XML

<output_list>
            <output_name>name_F</output_name>
            <output_category>Ferrari</output_category>
            <output_name>name_P</output_name>
            <output_category>Porsche</output_category>
            <output_name>name_L</output_name>
            <output_category>Lamborghini</output_category>
</output_list>

我想在节点&#34; output_name&#34;中获取文本值。和&#34; output_category&#34;使用for循环。

我使用以下XSL

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

<xsl:template match="/" >
<xmlns:swe="http://www.opengis.net/swe/2.0" 
xmlns:sml="http://www.opengis.net/sensorml/2.0">
        <sml:OutputList>    
         <xsl:for-each select="//output_list/output_name">
        <xsl:variable name="my_output_name" select="text()"/>
        <xsl:variable name="my_output_category" select="//output_list/output_category"/>
         <sml:output name="{$my_output_name}">
        <swe:Category definition="{$my_output_category}">
         </swe:Category>
        </sml:output>
         </xsl:for-each>
        </sml:OutputList>

</xsl:stylesheet>

我只能获得&#34; my_output_name&#34;的正确名称。变量。第二个变量只获得第一个值,并且相对于&#34; my_output_name&#34;它不会改变。变量。

我知道使用te​​xt()我只能得到当前节点的值。

您能否告诉我如何修复此代码以获取相关变量?

提前致谢

1 个答案:

答案 0 :(得分:2)

我猜你想要做的事情(因为你没有发布预期的结果):

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:template match="/output_list" >
    <sml:OutputList xmlns:sml="http://www.opengis.net/sensorml/2.0" xmlns:swe="http://www.opengis.net/swe/2.0">    
        <xsl:for-each select="output_name">
            <sml:output name="{.}">
                <swe:Category definition="{following-sibling::output_category[1]}"/>
            </sml:output>
        </xsl:for-each>
    </sml:OutputList>
</xsl:template>

</xsl:stylesheet>

得到:

<?xml version="1.0" encoding="UTF-8"?>
<sml:OutputList xmlns:sml="http://www.opengis.net/sensorml/2.0" xmlns:swe="http://www.opengis.net/swe/2.0">
  <sml:output name="name_F">
    <swe:Category definition="Ferrari"/>
  </sml:output>
  <sml:output name="name_P">
    <swe:Category definition="Porsche"/>
  </sml:output>
  <sml:output name="name_L">
    <swe:Category definition="Lamborghini"/>
  </sml:output>
</sml:OutputList>