Xquery - 使用XMLtable从XML中选择值

时间:2011-05-13 19:29:24

标签: xml db2 xquery

我想使用XQuery在以下XML中显示FrequencyCdvalue="01"city type="first"的值。

你能帮助我吗

<Envelope>
<Arrangement>
<FrequencyCd value="01">first first</FrequencyCd> 
<FrequencyCd value="02">first second</FrequencyCd> 
<contactinfo> <Address>
<street>234 Rolling Lane</street> 
<city type="first">Rockport</city> 
</Address>
<email>love2fish@finmail.com</email> 
</contactinfo>
</Arrangement>
<Arrangement>
<FrequencyCd value="03">second first</FrequencyCd> 
<FrequencyCd value="04">second second</FrequencyCd> 
<contactinfo>
<Address>
<street>234 Straight Lane</street> 
<city type="first">Crackport</city> 
</Address>
<email>hate2fish@finmail.com</email> 
</contactinfo>
</Arrangement>
</Envelope>

1 个答案:

答案 0 :(得分:2)

这种方法在内部粉碎了更多行,但允许将复合过滤条件(FrequencyCd和City的条件)实现为碎片XML数据的SQL表示(XMLTABLE函数的输出)上的简单WHERE子句。

with origxml(xdoc) AS (VALUES XMLPARSE( DOCUMENT 
    '<Envelope>
    <Arrangement>
    <FrequencyCd value="01">first first</FrequencyCd> 
    <FrequencyCd value="02">first second</FrequencyCd> 
    <contactinfo> <Address>
    <street>234 Rolling Lane</street> 
    <city type="first">Rockport</city> 
    </Address>
    <email>love2fish@finmail.com</email> 
    </contactinfo>
    </Arrangement>
    <Arrangement>
    <FrequencyCd value="03">second first</FrequencyCd> 
    <FrequencyCd value="04">second second</FrequencyCd> 
    <contactinfo>
    <Address>
    <street>234 Straight Lane</street> 
    <city type="first">Crackport</city> 
    </Address>
    <email>hate2fish@finmail.com</email> 
    </contactinfo>
    </Arrangement>
    </Envelope>'
    )
)
SELECT filteredxml.FrequencyCd, filteredxml.City FROM origxml,
XMLTABLE ('$d/Envelope/Arrangement' PASSING origxml.xdoc AS "d"
                COLUMNS
                FrequencyCd     VARCHAR(20) PATH    'FrequencyCd[@value="01"]/text()',
                City            VARCHAR(30) PATH    'contactinfo/Address/city[@type="first"]/text()'
            ) as filteredxml
WHERE filteredxml.FrequencyCd IS NOT NULL
AND filteredxml.City IS NOT NULL
;