2015-02-11 122 views
0

請檢查下面列出XML在PL/SQL的下方,輸出應該是這樣的:解析XML在PL/SQL查詢屬性

CITY_NAME POPULATION 
MUMBAI 6780000 
DELHI 5100000 
HYDERABAD 2480000 
CHENNAI 6100000 

我使用下面的查詢,但有沒有更好的方式來處理,而不是加入rownum。我承認XML格式可以更好地處理XML屬性。

WITH t as (select XMLTYPE(' 
<ROOT> 
    <CITY_INFO> 
     <CITY> 
      <CITY_NAME Value="MUMBAI"/> 
      <POPULATION Value="6780000" OldValue=""/> 
     </CITY> 
     <CITY> 
      <CITY_NAME Value="DELHI"/> 
      <POPULATION Value="5100000" OldValue=""/> 
     </CITY> 
    </CITY_INFO> 
    <CITY_INFO> 
     <CITY> 
      <CITY_NAME Value="HYDERABAD"/> 
      <POPULATION Value="2480000" OldValue=""/> 
     </CITY> 
     <CITY> 
      <CITY_NAME Value="CHENNAI"/> 
      <POPULATION Value="6100000" OldValue=""/> 
     </CITY> 
    </CITY_INFO> 
</ROOT> 
') as xml from dual) 
select a.CITY_NAME, b.population from (select c.*, rownum as row_num 
from t 
      ,XMLTABLE('/ROOT/CITY_INFO/CITY/CITY_NAME' 
       PASSING t.xml 
       COLUMNS CITY_NAME VARCHAR2(100) PATH '/CITY_NAME/@Value' 
      ) c) a, 
      (select pop.*, rownum as row_num 
      from t 
      ,XMLTABLE('/ROOT/CITY_INFO/CITY/POPULATION' 
       PASSING t.xml 
       COLUMNS POPULATION NUMBER PATH '/POPULATION/@Value' 
      ) pop) b where a.row_num = b.row_num 
+0

你是否得到任何錯誤,或者你的當前輸出不是「應該」?將這些細節添加到您的問題。如果您的當前輸出不同於添加當前輸出。 – Ram 2015-02-11 15:03:27

+0

查詢的輸出與預期相同,但rownum上的innerjoin看起來並不乾淨。下面發佈的答案可以在不解析兩次並加入的情況下實現輸出。 – 2015-02-11 15:43:38

回答

2

CITY_NAMEPOPULATION節點之前在XMLTABLE改變「根路徑」是的水平,並通過//引用CITY_NAMEPOPULATION節點,下面的工作對我來說:

WITH t as (select XMLTYPE(' 
<ROOT> 
    <CITY_INFO> 
     <CITY> 
      <CITY_NAME Value="MUMBAI"/> 
      <POPULATION Value="6780000" OldValue=""/> 
     </CITY> 
     <CITY> 
      <CITY_NAME Value="DELHI"/> 
      <POPULATION Value="5100000" OldValue=""/> 
     </CITY> 
    </CITY_INFO> 
    <CITY_INFO> 
     <CITY> 
      <CITY_NAME Value="HYDERABAD"/> 
      <POPULATION Value="2480000" OldValue=""/> 
     </CITY> 
     <CITY> 
      <CITY_NAME Value="CHENNAI"/> 
      <POPULATION Value="6100000" OldValue=""/> 
     </CITY> 
    </CITY_INFO> 
</ROOT> 
') as xml from dual) 
select a.CITY_NAME, a.population 
from t, 
     XMLTABLE('/ROOT/CITY_INFO/CITY' 
       PASSING t.xml 
       COLUMNS CITY_NAME VARCHAR2(100) PATH '//CITY_NAME/@Value', 
       POPULATION NUMBER PATH '//POPULATION/@Value' 
      ) a; 

CITY_NAME   POPULATION 
-------------------- ---------- 
MUMBAI     6780000 
DELHI     5100000 
HYDERABAD    2480000 
CHENNAI     6100000 
+0

謝謝你的作品。對不起,不能投票,因爲我是一個新人 – 2015-02-11 15:34:32

+0

@KrishY - 你仍然可以接受這個答案,[通過點擊投票按鈕下的複選標記](http://stackoverflow.com/help/someone-answers)。 – 2015-02-11 16:27:04