Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

xml - how to use xmltable in oracle?

I am using Oracle's XML DB to create user profiles. I stored user profiles in a single XMLTYPE column with other relational columns (id, username, password) in the table. The XML is of the following format:

<profile>
<subject>I
       <action>like
           <object>sports</object>
               ...
           <object>music</object
       </action>
    </subject>
</profile>

I used the following query,

SELECT *
FROM user,
XMLTABLE(
 '//profile'
 PASSING user.profile
 return COLUMNS action VARCHAR2(20) PATH '/subject/action',
         object VARCHAR2(30) PATH '/subject/action/object'
);

which gives me nothing. How could I make this thing work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

action and object on your example aren't on the same level, so your query has to perform additional steps. Here's an example:

SQL> create table users (id number, profile xmltype);

Table created.

SQL> insert into users values (1, XMLTYPE('<profile>
  2      <subject>I
  3         <action>like
  4             <object>sports</object>
  5             <object>music</object>
  6         </action>
  7      </subject>
  8  </profile>'));

1 row created.

SQL> select u.id, x.action, x.object.getStringVal()
  2    from users u,
  3         XMLTABLE('/profile/subject/action'
  4                  passing u.profile
  5                  columns action VARCHAR2(30) PATH 'text()',
  6                          object XMLTYPE PATH 'object') x;

ID  ACTION  X.OBJECT.GETSTRINGVAL()
--- ------- --------------------------------------------------
1   like    <object>sports</object> <object>music</object>

As you can see we got the node, not really what you want so we add an XMLTABLE:

SQL> select u.id, x.action, y.object
  2    from users u,
  3         XMLTABLE('/profile/subject/action'
  4                  passing u.profile
  5                  columns action VARCHAR2(30) PATH 'text()',
  6                          object XMLTYPE PATH 'object') x,
  7         XMLTABLE('/object'
  8                  passing x.object
  9                  columns object VARCHAR2(30) PATH '.') y;

ID  ACTION  OBJECT
--- ------- -------
1   like    sports
1   like    music

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...