xmltype - 删除没有子节点的父节点

xmltype - delete parent node without child

是否可以删除 xmltype 变量中没有子节点的父节点?

例如:

declare
  v1 xmltype := xmltype('<root>
                           <parent1>
                             <child>1</child>
                             <child>2</child>
                           </parent1>
                           <parent2>
                             <child2>3</child2>
                           </parent2>
                         </root>');
begin
  -- some code...
  dbms_output.put_line(v1.getClobVal());
end;

我的目的是在输出中得到这个:

<root>
  <child>1</child>
  <child>2</child>
  <parent2>
    <child2>3</child2>
  </parent2>
</root>

我尝试使用 deleteXML 函数,但它也删除了子节点...

所以,如果有人能帮我解决这个问题,我将不胜感激:)

可以使用 DELETEXML 删除节点,例如:

select DELETEXML(v1,'/root/parent1') into v1 from dual;

但是删除parent1也会删除parent 1的所有子节点。 如果要保留 parent1 的子节点,首先必须在删除 parent1 之前制作这些节点的副本。你可以这样做:

declare
  v1 xmltype := xmltype('<root>
                           <parent1>
                             <child>1</child>
                             <child>2</child>
                           </parent1>
                           <parent2>
                             <child2>3</child2>
                           </parent2>
                         </root>');
begin

  --Append all child nodes of parent1 as child nodes of root before the parent2 node
  select insertxmlbefore(v1, '/root/parent2',extract(v1,'/root/parent1/child::node()')) into v1 from dual;

  --remove parent 1
  select DELETEXML(v1,'/root/parent1') into v1 from dual;

  dbms_output.put_line(v1.getClobVal());

end;

这会给你:

<root>
    <child>1</child>
    <child>2</child>
    <parent2>
        <child2>3</child2>
    </parent2>
</root>

希望对您有所帮助。