簡體   English   中英

在 Db2 (SQL/XML) 中使用 xmlquery 從 xml 中選擇元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM