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
1.0k views
in Technique[技术] by (71.8m points)

xml - Concatenate XMLType nodes in Oracle query

I have a CLOB column that contains XML type data. For example XML data is:

<A><B>123</b><C>456</C><B>789</b></A>

I have tried the concat function:

concat(xmltype (a.xml).EXTRACT ('//B/text()').getStringVal (),';'))

or

xmltype (a.xml).EXTRACT (concat('//B/text()',';').getStringVal ()))

But they are giving ";" at end only not after each <B> tag.

I am currently using

xmltype (a.xml).EXTRACT ('//B/text()').getStringVal () 

I want to concatenate all <B> with ; and expected result should be 123;789

Please suggest me how can I concatenate my data.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The concat() SQL function concatenates two values, so it's just appending the semicolon to each extracted value independently. But you're really trying to do string aggregation of the results (which could, presumably, really be more than two extracted values).

You can use XMLQuery instead of extract, and use an XPath string-join() function to do the concatentation:

XMLQuery('string-join(/A/B, ";")' passing xmltype(a.xml) returning content)

Demo with fixed XMl end-node tags:

-- CTE for sample data
with a (xml) as (
  select '<A><B>123</B><C>456</C><B>789</B></A>' from dual
)
-- actual query
select XMLQuery('string-join(/A/B, ";")' passing xmltype(a.xml) returning content) as result
from a;

RESULT
------------------------------
123;789

You could also extract all of the individual <B> values using XMLTable, and then use SQL-level aggregation:

-- CTE for sample data
with a (xml) as (
  select '<A><B>123</B><C>456</C><B>789</B></A>' from dual
)
-- actual query
select listagg(x.b, ';') within group (order by null) as result
from a
cross join XMLTable('/A/B' passing xmltype(a.xml) columns b number path '.') x;

RESULT
------------------------------
123;789

which gives you more flexibility and would allow grouping by other node values more easily, but that doesn't seem to be needed here based on your example value.


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

...