update将节点内的文本转换为子节点

update将节点内的文本转换为子节点

本文介绍了如何使用xquery update将节点内的文本转换为子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似xml的文件

I have a xml document like

<root>
  <first>
    First Level
    <second>
      second level
       <third>
         Third Level
       </third>
    </second>
    <second2>
      another second level
    </second2>
  </first>
</root>

如何使用所有节点转换此文档,这意味着如果节点包含textchild node,则使用xquery-update childtext ) >

How to convert this document with all nodes, that means if a node contains text and child node convert text into a child node (let's say childtext) using xquery-update

<root>
  <first>
    <childtext>First Level</childtext>
    <second>
      <childtext>second level</childtext>
       <third>
         Third Level
       </third>
    </second>
    <second2>
      another second level
    </second2>
  </first>
</root>

这是我尝试过的:

let $a :=
<root>
  <first>
    First Level
    <second>
      second level
       <third>
         Third Level
       </third>
    </second>
    <second2>
      another second level
    </second2>
  </first>
</root>
return
copy $i := $a
modify (
  for $x in $i/descendant-or-self::*
  return (
    if($x/text() and exists($x/*)) then (
      insert node <childtext>
        {$x/text()}
       </childtext> as first into $x
        (: here should be some code to delete the text only:)
    ) else ()
  )
)
return $i

我无法删除具有同级节点的文本.

I could not delete the text which has sibling node.

推荐答案

要替换元素,应仅使用replace构造,而不是插入新元素并删除旧元素.对我来说似乎简单得多:

As you want to replace an element, you should simply use the replace construct, instead of inserting the new element and deleting the old one. Seems much simpler to me:

copy $i := $a
modify (
  for $x in $i/descendant-or-self::*[exists(*)]/text()
  return replace node $x with <childtext>{$x}</childtext>
)
return $i

这篇关于如何使用xquery update将节点内的文本转换为子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 21:02