[英]Selecting element from xml using xmlquery in Db2 (SQL/XML)
我在 Db2 中创建了这样的表:
create table xml_file(data xml not null)
这是 xml 的确切结构:
<?xml version="1.0" encoding="UTF-8" ?>
<student id="20140021">
<name>Tom</name>
<surname>Johnson</surname>
<birth_date>"05/11/1995"</birth_date>
<birth_place>"Miami"</birth_place>
<points>9.45</points>
</student>
我想为所有姓名为 Ben 且出生地为芝加哥的学生提供 ID、姓名、姓氏和积分。
我写了这样的东西:
select xmlquery('$DATA/student/data(@id)') as ID,
xmlquery('$DATA/student/name/text()') as NAME,
xmlquery('$DATA/student/surname/text()') as SURNAME,
xmlquery('$DATA/student/points/text()') as POINTS
from xml_file
where xmlexists('$DATA/student[birth_place = "Chicago"]')
and xmlexists('$DATA/student[name = "Ben"]');
我得到的只是这条消息: “FETCHED 0 RECORDS, 0 RECORDS SHOWN” (这是在 IBM Data Studio 中)。
有人能告诉我我做错了什么吗?
尝试这个:
/*
WITH xml_file (data) AS
(
VALUES
XMLPARSE
(DOCUMENT '<?xml version="1.0" encoding="UTF-8" ?>
<student id="20140021">
<name>Tom</name>
<surname>Johnson</surname>
<birth_date>"05/11/1995"</birth_date>
<birth_place>"Miami"</birth_place>
<points>9.45</points>
</student>'
)
)
*/
SELECT X.*
FROM
xml_file V
, XMLTABLE
('$doc/student' PASSING V.data AS "doc"
COLUMNS
ID INT PATH '@id'
, NAME VARCHAR(20) PATH 'name'
, SURNAME VARCHAR(20) PATH 'surname'
, POINTS DEC(5, 2) PATH 'points'
) X
WHERE XMLEXISTS('$doc/student[birth_place = """Miami""" and name = "Tom"]' PASSING V.data AS "doc");
尝试用一个替换你的两个where xmlexists
(这与问题中的示例 xml 一起使用,而不是你的代码):
where xmlexists('$DATA//student[birth_place/text()['Miami']][name/text()["Tom"]]');
或者,需要两个:
where xmlexists('$DATA/student[birth_place/text()['Miami']]')
and xmlexists('$DATA/student[name/text()["Tom"]]');
看看是否有效。
出生地元素包含导致 XPath 评估错误的双引号。 为避免这种情况,请将where xmlexists('$DATA/student[birth_place = "Chicago"]')
替换为以下 XPath 表达式之一:
XPath 1.0 友好:
where xmlexists('$DATA/student/birth_place[substring(.,2,string-length(/student/birth_place)-2)="Chicago"]')
XPath 2.0 友好:
where xmlexists('$DATA/student/birth_place[translate(.,codepoints-to-string(34),"")="Chicago"]')
XPath 用于测试您的样本数据:
/student/birth_place[substring(.,2,string-length(/student/birth_place)-2)="Miami"]
/student/birth_place[translate(.,codepoints-to-string(34),"")="Miami"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.