2

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.