问题
I have problem with insert xmltype into another xmltype in specified place in pl/sql.
First variable v_xml has the form:
<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
</ord>
And the second v_xml2:
<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>
My purpose is get something like this:
<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
<!-- put the second variable in this place - after closing <head> tag -->
<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>
</ord>
What shoud I do with my code?
declare
v_xml xmltype;
v_xml2 xmltype;
begin
-- some code
-- some code
-- v_xml and v_xml2 has the form as I define above
end;
Is anyone able to help me with this problem? As I know there are functions like insertchildxml, appendchildxml or something like this... I found few solution in pure SQL, but I don't know how to move this in PL/SQL.
Thanks!
回答1:
You can use mentioned appendChildXML, like here:
declare
v_xml xmltype := xmltype('<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
</ord>');
v_xml2 xmltype:= xmltype('<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>');
v_output xmltype;
begin
select appendChildXML(v_xml, 'ord', v_xml2)
into v_output from dual;
-- output result
dbms_output.put_line( substr( v_output.getclobval(), 1, 1000 ) );
end;
Output:
<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>
</ord>
回答2:
appendChildXML is deprecated at 12.1
So here is a solution using XMLQuery
DECLARE
l_head_xml XMLTYPE := XMLTYPE.CREATEXML('<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
</ord>');
l_pos_xml XMLTYPE := XMLTYPE.CREATEXML('<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>');
l_complete_xml XMLTYPE;
BEGIN
SELECT XMLQUERY('for $i in $h/ord/head
return <ord>
{$i}
{for $j in $p/pos
return $j}
</ord>'
PASSING l_head_xml AS "h",
l_pos_xml AS "p"
RETURNING CONTENT)
INTO l_complete_xml
FROM dual;
dbms_output.put_line(l_complete_xml.getstringval());
END;
回答3:
Here is one solution using XMLQuery
DECLARE
l_src XMLTYPE:=XMLTYPE('<ord>
<head>
<ord_code>123</ord_code>
<ord_date>01-01-2015</ord_date>
</head>
</ord>');
l_dst XMLTYPE:=XMLTYPE('<pos>
<pos_code>456</pos_code>
<pos_desc>description</pos_desc>
</pos>');
l_final CLOB;
BEGIN
SELECT XMLQUERY('copy $tmp := $p1 modify
insert node $p2 as last into $tmp
return $tmp' PASSING l_src as "p1",l_dst as "p2" RETURNING CONTENT).getClobval() into l_final from dual;
DBMS_OUTPUT.PUT_LINE(l_final);
END;
来源:https://stackoverflow.com/questions/29821779/insert-xmltype-into-xmltype-in-specified-place-pl-sql