使用XPath进行XLST查询

时间:2018-03-23 09:08:20

标签: xslt xpath

输入XML:

<?xml version="1.0" encoding="UTF-8"?>
<countries>
  <country name="Afghanistan" population="22664136" area="647500">
    <language percentage="11">Turkic</language>
    <language percentage="35">Pashtu</language>
    <language percentage="50">Afghan Persian</language>
  </country>
  <country name="Albania" population="3249136" area="28750"/>
  <country name="Algeria" population="29183032" area="2381740">
    <city>
      <name>Algiers</name>
      <population>1507241</population>
    </city>
  </country>
  <country name="American Samoa" population="59566" area="199"/>
  <country name="Andorra" population="72766" area="450"/>
  <country name="Angola" population="10342899" area="1246700"/>
  <country name="Anguilla" population="10424" area="91">
    <language percentage="100">English</language>
  </country>
  <country name="Antigua and Barbuda" population="65647" area="440">
    <language percentage="100">English</language>
  </country>
 .....

您好首先使用此XSLT我想获得其语言以'ian'结尾的国家/地区的名称(如俄语......),所以我有这个XSLT:

<?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"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:template match="/">
        <countries>
            <xsl:for-each select="countries/country[substring('language', 3) = 'ian']">
                <country>
                    <nom><xsl:value-of select="@name"/></nom>
                    <idiomes>
                        <xsl:value-of select="language"/>
                    </idiomes>
                </country>
            </xsl:for-each>
        </countries>
    </xsl:template>
</xsl:stylesheet>

请有人帮帮我..

2 个答案:

答案 0 :(得分:1)

尝试使用以下XPath来获取coutrylanguage个结尾的"ian"个节点,并使用countries/country[language[substring(., string-length(.) - 2)="ian"]]

language[substring(., string-length(.) - 2)="ian"]

一些澄清:

language谓词表示 "ian"哪个文字内容最后3个字符等于string-length(.) - 2

language表示从语言长度开始计算字符数 - 2

例如,如果"Pashtu"内容为string-length(.) - 2(长度为6个字符),则6 - 2 = 44,因此我们应从索引"h"开始是1(请注意,在XPath中,第一个索引是0,而不是4)。从索引"htu"开始,我们的子字符串将为"htu" != "ian"itemDestroyed

答案 1 :(得分:1)

如果你确实使用了version="2.0"的XSLT,那么使用language[ends-with(., 'ian')]似乎是检查ian语句元素的最简单方法。