在PL / SQL查询中解析XML属性

时间:2015-02-11 14:39:46

标签: xml oracle

请在下面的PL / SQL中检查下面的XML,输出应该是这样的:

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

1 个答案:

答案 0 :(得分:2)

通过更改&#34;根路径&#34;在xmltable中,作为CITY_NAMEPOPULATION节点之前的级别,并通过CITY_NAME引用POPULATION//节点,以下内容适用于我:

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