简体   繁体   中英

Extracting XML node values in a nested XML in PL SQL

I have a XMLTYPE like this

<QuestionCategory>
   <categoryId>
   </categoryid>
   <questions>
      <question>
        <questionId>1</questionId>
        <questiontext>abc</questiontext>
      </question>
      <question>
      </question>
      <question>
      </question>
   </questions>  
</QuestionCategory>

I need to get the question Ids from this XML and insert them in a table. How can I do that. I have tried Looping through the 'question' nodes.

You can use an XMLTable to extract relational rows of information from the XML structure. You've tagged the question with that so you may just be stuck trying to implement it.

With the simple outline you showed you could do something like:

select *
from xmltable('/QuestionCategory/questions/question'
  passing your_xmltype_value
  columns question_id number path 'questionId',
    question_text varchar2(20) path 'questiontext'
);

Making the size of the question text variable as large as your data requires, of course, presumbaly to match your existing table structure - if you want to store the text at all, that is.

If the XMLType is a column in a table you can pass it with a join:

select x.*
from your_table
cross join xmltable('/QuestionCategory/questions/question'
  passing your_table.your_xmltype_column
  columns question_id number path 'questionId',
    question_text varchar2(20) path 'questiontext'
);

For example, with a fixed document:

select *
from xmltable('/QuestionCategory/questions/question'
  passing xmltype('<QuestionCategory>
   <categoryId>
   </categoryId>
   <questions>
      <question>
        <questionId>1</questionId>
        <questiontext>abc</questiontext>
      </question>
      <question>
        <questionId>2</questionId>
        <questiontext>def</questiontext>
      </question>
      <question>
        <questionId>3</questionId>
        <questiontext>ghi</questiontext>
      </question>
   </questions>  
</QuestionCategory>')
  columns question_id number path 'questionId',
    question_text varchar2(20) path 'questiontext'
);

QUESTION_ID QUESTION_TEXT       
----------- --------------------
          1 abc                  
          2 def                  
          3 ghi                  

You can easily then use that as the basis for an insert ... select construct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM