【问题标题】:Appending parent element along with its child tags to new etree using lxml使用 lxml 将父元素及其子标签附加到新的 etree
【发布时间】:2017-11-24 10:08:01
【问题描述】:

只是一个简单的问题。对不起,如果它是基本的,我尝试谷歌搜索但没有得到任何有用的东西。这是我的查询。我有 2 个 LXML etree,PFB XML-1:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
   <child c="1">
      <e1>abc</e1>
      <e2>abc</e2>
      <e3>abc</e3>
      <e4>
         <e41>xyz</e41>
         <e41>zyx</e41>
      </e4>
   </child>
   <child c="2">
      <e1>abc</e1>
      <e2>abc</e2>
      <e3>abc</e3>
      <e4>
         <e41>xyz</e41>
         <e41>zyx</e41>
      </e4>
   </child>
</parent>

XML-2:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <child c="3">
      <e1>abc</e1>
      <e2>abc</e2>
      <e3>abc</e3>
      <e4>
         <e41>xyz</e41>
         <e41>zyx</e41>
      </e4>
    </child>
</parent>

最终结果:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <child c="3">
      <e1>abc</e1>
      <e2>abc</e2>
      <e3>abc</e3>
      <e4>
         <e41>xyz</e41>
         <e41>zyx</e41>
      </e4>
    </child>
    <child c="1">
      <e1>abc</e1>
      <e2>abc</e2>
      <e3>abc</e3>
      <e4>
         <e41>xyz</e41>
         <e41>zyx</e41>
      </e4>
   </child>
</parent>

现在我想在 XML-2 中附加“child c='1'”元素及其来自 XML-1 的子元素。对,我正在遍历它的子元素并附加 XML-2。有没有办法在不循环的情况下附加 XML-2。我的意思是一口气。提前致谢。不要问我尝试了什么。我当前的代码(循环遍历元素)工作正常。而且我不确定是否有可能。

【问题讨论】:

  • 发布最终结果
  • @RomanPerekhrest 刚刚添加了最终结果的样子。
  • (循环遍历元素 - 无需循环,只需 find 方法

标签: python-3.x lxml elementtree


【解决方案1】:

别介意伙计们,刚刚发现了 deepcopy。

如果您想将一个元素复制到 lxml.etree 中的不同位置,请考虑使用 Python 标准库中的复制模块创建一个独立的深层复制:

>>> from copy import deepcopy

>>> element = etree.Element("neu")
>>> element.append( deepcopy(root[1]) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    相关资源
    最近更新 更多