提问人:q4za4 提问时间:10/26/2023 最后编辑:MT0q4za4 更新时间:10/26/2023 访问量:32
XMLQUERY - 插入节点,当不为 null 时
XMLQUERY - insert node when is not null
问:
示例代码:
declare
l_xml_response xmltype;
i_cl clob;
l_flag number(1) := 1;
l_product_type varchar2(5) := 'P';
begin
l_xml_response := xmltype('<?xml version="1.0"?>
<main-node>
<node1>
<node2>
<node3 product-type="PGZ">
<id>3</id>
</node3>
</node2>
</node1>
</main-node>');
SELECT XMLQUERY
('
copy $res := $req
modify insert nodes
(
<amount>{$amount1}</amount>,
<amount-1>{$amount2}</amount-1>,
<amount-2>{$amount3}</amount-2>,
<amount-3>{$amount4}</amount-3>
)
after $res/main-node/node1/node2/node3/id
return $res
'
PASSING l_xml_response AS "req",
1 AS "amount1",
2 AS "amount2",
3 AS "amount3",
CASE
WHEN NVL(l_flag, 0) = 1 AND l_product_type = 'P' THEN 456
END AS "amount4"
RETURNING CONTENT
)
INTO l_xml_response
FROM dual;
SELECT XMLSERIALIZE
(
CONTENT l_xml_response
AS CLOB
VERSION '1.0'
INDENT SIZE = 2
HIDE DEFAULTS
)
INTO i_cl
FROM dual;
dbms_output.put_line( i_cl);
end;
/
我试图实现的是仅在不为空时才添加节点 amount4。此 xquery 添加空节点 ( )。它不会破坏任何东西,只是尽量不发送不必要的空节点。<amount-3/>
Mayby有人对此有一些快速,聪明的解决方案。
谢谢。
答:
1赞
MT0
10/26/2023
#1
在 FLWOR 表达式中使用:if .. then .. else ..
declare
l_xml_response xmltype;
i_cl clob;
l_flag number(1) := 1;
l_product_type varchar2(5) := 'P';
begin
l_xml_response := xmltype('<?xml version="1.0"?>
<main-node>
<node1>
<node2>
<node3 product-type="PGZ">
<id>3</id>
</node3>
</node2>
</node1>
</main-node>');
SELECT XMLQUERY
('
copy $res := $req
modify insert nodes
(
<amount>{$amount1}</amount>,
<amount-1>{$amount2}</amount-1>,
<amount-2>{$amount3}</amount-2>,
if ($amount4)
then <amount-3>{$amount4}</amount-3>
else ()
)
after $res/main-node/node1/node2/node3/id
return $res
'
PASSING l_xml_response AS "req",
1 AS "amount1",
2 AS "amount2",
3 AS "amount3",
NULL AS "amount4"
RETURNING CONTENT
)
INTO l_xml_response
FROM dual;
SELECT XMLSERIALIZE
(
CONTENT l_xml_response
AS CLOB
VERSION '1.0'
INDENT SIZE = 2
HIDE DEFAULTS
)
INTO i_cl
FROM dual;
dbms_output.put_line( i_cl);
end;
/
输出:
<?xml version="1.0"?> <main-node> <node1> <node2> <node3 product-type="PGZ"> <id>3</id> <amount>1</amount> <amount-1>2</amount-1> <amount-2>3</amount-2> </node3> </node2> </node1> </main-node>
评论
0赞
q4za4
10/26/2023
我试过了,但似乎我在语法上做错了。谢谢!
0赞
MT0
10/26/2023
@q4za4 问题中链接的小提琴显示它有效,所以我不确定我是否理解为什么您在语法方面遇到问题。
评论