【问题标题】:BaseX XQUERY selecting nodes with the value of a specific attributeBaseX XQUERY 选择具有特定属性值的节点
【发布时间】:2021-07-31 20:14:13
【问题描述】:

XML 示例:


    <mondial>
        <continent id="f0_119" name="Europe"/>
        <continent id="f0_123" name="Asia"/>
        <continent id="f0_126" name="America"/>
        <continent id="f0_129" name="Australia/Oceania"/>
        <continent id="f0_132" name="Africa"/>
        <country id="f0_136" name="Albania" capital="f0_1461" population="3249136"
                 datacode="AL" total_area="28750" population_growth="1.34"
                 infant_mortality="49.2" gdp_agri="55" gdp_total="4100"
                 inflation="16" indep_date="28 11 1912"
                 government="emerging democracy" car_code="AL">
            <name>Albania</name>
            <city id="f0_1461" country="f0_136" longitude="10.7" latitude="46.2">
                <name>Tirane</name>
                <population year="87">192000</population>
            </city>
            <city id="f0_36498" country="f0_136" longitude="19.2" latitude="42.2">
                <name>Shkoder</name>
                <population year="87">62000</population>
                <located_at type="lake" water="f0_39058"/>
            </city>
        </country>
    </mondial>

for $x in //mondial/country/population
where $x/@year=87
return $x/name

我基本上试图从具有year=87 属性的节点&lt;population&gt; 返回&lt;name&gt;。我知道这听起来很令人困惑,我什至找不到这方面的文档我试过谷歌搜索如何使用该属性进行选择,但我似乎无法返回任何内容。

【问题讨论】:

  • 我正确地格式化了你的 XML ,所以你可以很容易地看到它的结构。

标签: xml xquery basex


【解决方案1】:

您可以使用单个 XPath 获取所需信息

//city[population/@year=87]/name

Live Demo (xqueryfiddle)

【讨论】:

    【解决方案2】:

    请注意,您的 XML 文档中的 population 元素是 city 元素的子元素。接下来,您尝试循环遍历 population 元素,最好将此路径步骤移动到 where 子句中。返回城市名称的一种解决方案如下:

    for $city in /mondial/country/city
    where $city/population/@year = 87
    return $city/name
    

    【讨论】:

    • 你有点晚了,但你和@Yitzhak Khabinsky 的回答是对的,谢谢!
    【解决方案3】:

    请尝试以下 XQuery。

    XQuery

    for $x in //mondial/country/city
    where $x/population/@year=87
    return $x/name
    

    【讨论】:

    • 它确实返回了&lt;population&gt; 的值,但我需要&lt;name&gt; 这可能吗?
    • @OscarCubz,我调整了答案。
    • 谢谢!正是我需要的
    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多