如何执行XPATH条件SUM

时间:2015-05-11 20:46:30

标签: xml xpath-2.0 xquery-3.0 xpath-3.0

我试图使用过滤器构建一个xpath求和表达式,该过滤器将过滤时间帧和单位的秒数。我觉得这很简单,但似乎无法抓住它。

假设我有一个XML文档,如:

<root>
    <hourly>
        <hour>
            <unit>1</unit>
            <timestamp>2015-05-02 00:00:00-0500</timestamp>
            <operationaltime>3600</operationaltime>
        </hour>
        <hour>
            <unit>1</unit>
            <timestamp>2015-05-02 01:00:00-0500</timestamp>
            <operationaltime>3113</operationaltime>
        </hour>
        <hour>
            <unit>2</unit>
            <timestamp>2015-05-02 00:00:00-0500</timestamp>
            <operationaltime>1809</operationaltime>
        </hour>
        <hour>
            <unit>2</unit>
            <timestamp>2015-05-02 01:00:00-0500</timestamp>
            <operationaltime>3444</operationaltime>
        </hour>
    </hourly>
</root>

这就是我所拥有的:

sum(hourly/hour[/unit=2 and /timestamp='2015-05-02 01:00:00-0500']/operationaltime)

1 个答案:

答案 0 :(得分:4)

当您希望它们是相对路径时,请勿使用绝对路径。也就是说,当你说/unit=2时,它会回到上下文项的根;如果您希望它相对于小时,请使用./unit=2unit=2。因此:

declare context item := <root>
    <hourly>
        <hour>
            <unit>1</unit>
            <timestamp>2015-05-02 00:00:00-0500</timestamp>
            <operationaltime>3600</operationaltime>
        </hour>
        <hour>
            <unit>1</unit>
            <timestamp>2015-05-02 01:00:00-0500</timestamp>
            <operationaltime>3113</operationaltime>
        </hour>
        <hour>
            <unit>2</unit>
            <timestamp>2015-05-02 00:00:00-0500</timestamp>
            <operationaltime>1809</operationaltime>
        </hour>
        <hour>
            <unit>2</unit>
            <timestamp>2015-05-02 01:00:00-0500</timestamp>
            <operationaltime>3444</operationaltime>
        </hour>
    </hourly>
</root>;

sum(hourly/hour[unit=2 and timestamp='2015-05-02 01:00:00-0500']/operationaltime)

...产生3444的结果,看起来对我来说是正确的。