使用 python 从 XML 文件中删除元素

Delete Element from XML file using python

我一直在尝试删除 following Document 中的 structuredBody 元素(位于组件元素内),但我的代码似乎不起作用。

XML源文件结构简化:

<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
...
  <component>
    <structuredBody>
    ...
    ...
    </structuredBody>
  </component>
</ClinicalDocument>

这是我使用的代码:

import xml.etree.ElementTree as ET
from lxml import objectify, etree

cda_tree = etree.parse('ELGA-023-Entlassungsbrief_aerztlich_EIS-FullSupport.xml')
cda_root = cda_tree.getroot()
for e in cda_root: 
    ET.register_namespace("", "urn:hl7-org:v3")

for node in cda_tree.xpath('//component/structuredBody'):
    node.getparent().remove(node)

cda_tree.write('newXML.xml')

每当我 运行 代码时,newXML.xml 文件仍然有 structuredBody 元素。

提前致谢!

根据您最近的编辑,我认为您会发现问题在于您的 for 循环与任何节点都不匹配。您的文档不包含任何名为 componentstructuredBody 的元素。根元素上的 xmlns="urn:hl7-org:v3" 声明意味着文档中的所有元素默认存在于该特定命名空间中,因此在匹配元素时需要使用该命名空间:

from lxml import objectify, etree

cda_tree = etree.parse('data.xml')
cda_root = cda_tree.getroot()

ns = {
    'hl7': 'urn:hl7-org:v3',
}

for node in cda_tree.xpath('//hl7:component/hl7:structuredBody', namespaces=ns):
    node.getparent().remove(node)

cda_tree.write('newXML.xml')

使用上面的代码,如果输入是这样的:

<ClinicalDocument
    xmlns="urn:hl7-org:v3"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <component>
    <structuredBody>
    ...
    ...
    </structuredBody>
  </component>
</ClinicalDocument>

输出如下:

<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <component>
    </component>
</ClinicalDocument>