XQuery(XPath)根据数字计算子元素和组

时间:2014-01-29 11:55:51

标签: xpath xquery flwor

输入的示例XML文件和预期输出位于底部,需要帮助根据子元素的数量进行分组。

  <DashboardXML>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
          <Column>
            <ColumnOrder>3</ColumnOrder>
            <ColLabel><![CDATA[terst]]></ColLabel>       
        </Column>
    </DashboardXML>
    <DashboardXML>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
          <Column>
            <ColumnOrder>3</ColumnOrder>
            <ColLabel><![CDATA[terst]]></ColLabel>       
        </Column>
    </DashboardXML>
    <DashboardXML>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
    </DashboardXML>
    <DashboardXML>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
    </DashboardXML>
    <DashboardXML>
        <Column>
            <ColumnOrder>1</ColumnOrder>
            <ColLabel><![CDATA[test1]]></ColLabel>                
        </Column>
        <Column>
            <ColumnOrder>2</ColumnOrder>
            <ColLabel><![CDATA[t1est]]></ColLabel>       
        </Column>
    </DashboardXML>

上面是示例XML作为输入,下面是XQuery:

for $b in /DashboardXML where count($b/Column) > 0 order by count($b/Column) return <li>{count($b/Column)} </li>

查询产生以下输出(样本):

    <li>3</li>
    <li>3</li>
    <li>2</li>
    <li>4</li>
    <li>2</li>

现在问题是如何将输出分组如下:

2 = 2 (counts)
3 = 2 (counts)
4 = 1 (counts)

1 个答案:

答案 0 :(得分:1)

鉴于您正在使用支持XQuery 3.0的查询处理器,请使用group by子句。

for $b in $xml/DashboardXML
let $count := count($b/Column)
where $count > 0
order by $count descending
group by $count
return <li>{$b/DashboardName/text()} = {$count} ({count ($b) }) </li>

将输出

<li> = 1 (1) </li>
<li> = 2 (2) </li>

用于给出的输入(注意缺少的DashboardName元素,并且我更改了where子句以允许任何非零数量的Column子项。

相关问题