【问题标题】:xmltype - delete parent node without childxmltype - 删除没有子节点的父节点
【发布时间】:2015-04-24 10:27:57
【问题描述】:

这是否可以在 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 函数,但它也删除了子节点...

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

【问题讨论】:

  • 不,看来您需要将子节点复制到临时变量中,删除父节点,然后从临时变量中重新插入子节点。

标签: sql oracle plsql oracle11g


【解决方案1】:

可以使用 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>

希望对您有所帮助。

【讨论】:

  • 我的做法和你一样。但是,如果一步不可能做到这一点,那么你的答案是正确的。谢谢你的时间:)
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多