xpath - Xquery将元素的所有“内容”(text()+所有子节点)复制到新元素中

标签 xpath xquery

在Xquery 3.1中,我正在将XML文件(包含最初保存在SQL表中的数据)转换为另一种XML文件格式。通常,这非常简单,但是对于一个特定元素,我想将text()以及任何child节点及其各自的内容复制到一个新元素中。例如,我要转换以下XML:

<table tablename="collections">
  <record id="1">
    <field fieldname="id">1</field>
    <field fieldname="title">Quisque elementum cursus nunc non aliquam</field>
    <field fieldname="desc">Quisque elementum cursus nunc non aliquam; 
        also known under the title <i>Lorem ipsum dolor sit amet</i>.<br/> The 
       same author compiled a large encyclopedia <i>Liber de natura 
       rerum,</i> synthesizing much knowledge from his period.</field>
    <field fieldname="author">Thomas de Cantimpré</field>
   </record>
 </table>


变成:

 <list xml:id="collections">
   <item n="1">
    <list>
     <item type="title">Quisque elementum cursus nunc non aliquam</item>
     <item type="desc">Quisque elementum cursus nunc non aliquam; 
        also known under the title <i>Lorem ipsum dolor sit amet</i>.<br/> The 
       same author compiled a large encyclopedia <i>Liber de natura 
       rerum,</i> synthesizing much knowledge from his period.</item>
     <item type="author">Thomas de Cantimpré</item>
    </list>
    </item>
 </list>


总的来说,这并没有带来什么问题。但是,我对在元素text()中获取child和所有<field fieldname="desc">节点的问题感到困惑。 XPATH中的解决方案令我望而却步。

在此先感谢您的任何建议。

最佳答案

您对“所有内容”的口头描述将是XPath术语中的所有子节点,并且文本节点当然也是元素的子节点,就像子元素是子节点一样。要选择容器节点的所有子节点,您只需要在容器节点的上下文中使用node()例如/table/record/field[@fieldname="desc"]/node()选择输入样本的field fieldname="title"元素的所有子节点。

关于xpath - Xquery将元素的所有“内容”(text()+所有子节点)复制到新元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112010/

相关文章:

javascript - 评估 Chrome 中的 xpath 表达式

xml - XPath:仅当所有子节点都具有特定值时才获取父节点的属性

xpath - 使用 XPath/XQuery 获取元素名称

sql - SQL Server 中的 XML 循环

xml - XQuery 同时获取和插入

python - 尝试写入 CSV,但某些字段在 python 的 scrapy 中被排除

xml - 如何将 xpath 传递到 xquery 函数声明中

java - 如何将 XQuery 结果存储为 BaseX 中的新文档

xml - 如何修复丑陋的 XQuery 输出?

c# - 使用 C# XmlDocument 选择相对 XPath 节点