如何解决使用python从XML文件中删除元素
我一直在尝试删除 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 文件仍然具有结构化Body 元素。
提前致谢!
解决方法
根据您最近的编辑,我认为您会发现问题在于您的 for
循环不匹配任何节点。您的文档不包含任何名为 component
或 structuredBody
的元素。根元素上的 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。