【发布时间】:2021-05-19 20:32:14
【问题描述】:
我正在尝试从 XML 中删除空 XML 元素,但是对于具有属性但没有文本值的元素存在问题。我可以成功删除空 XML 元素,但无法在最终 XML 中保留具有属性的元素。我想基本上清理 XML 并完全删除没有文本值的空节点,但保留具有属性的节点。
以下是我正在使用的脚本,以及输入和(所需的)输出 XML……任何帮助都非常感谢!
脚本:
from lxml import etree
import os
path = "C:\\users\\mdl518\\Desktop\\"
### Removing empty XML elements
tree = etree.parse(os.path.join(path,"my_file.xml"))
for elem in tree.xpath('//*[not(node())]'):
elem.getparent().remove(elem):
with open(".//new_file.xml","wb") as f:
f.write(etree.tostring(tree, xml_declaration=True, encoding='utf-8')) ## Removes empty XML elements, including the elements with attributes
输入 XML:
<?xml version='1.0' encoding='utf-8'?>
<nas:metadata xmlns:nas="http://www.arcgis.com/schema/nas/base"
xmlns:mcc="http://standards.org/iso/19115/-3/mcc/1.0"
xmlns:mdl="http://standards.org/iso/19115/-3/mdl/1.0"
xmlns:mnl="http://standards.org/iso/19115/-3/mnl/1.0">
xmlns:lan="http://standards.org/iso/19115/-3/lan/1.0">
xmlns:lis="http://standards.org/iso/19115/-3/lis/1.0">
xmlns:gam="http://standards.org/iso/19115/-3/gam/1.0">
<mdl:metadataIdentifier>
<mcc:MD_Identifier>
<mnl:type>
<gam:String>The Metadata File</gam:String>
</mnl:type>
<mnl:description codeList="http://arcgis.com/codelist/ScopeCode" codeListValue="dataset"/>
<mnl:address>
<mnl:defaultLocale>
</mnl:defaultLocale>
</mnl:address>
<lan:language>
<lan:type>
<lis:name>English</lis:name>
</lan:type>
</lan:language>
</mcc:MD_Identifier>
<mcc:contactInfo>
<mdl:POC>
<mnl:name>
<lis:person>Tom</lis:person>
</mnl:name>
<mnl:age>
</mnl:age>
<mnl:status>
</mnl:status>
</mdl:POC>
</mcc:contactInfo>
</mdl:metadataIdentifier>
</nas:metadata>
输出 XML:
<?xml version='1.0' encoding='utf-8'?>
<nas:metadata xmlns:nas="http://www.arcgis.com/schema/nas/base"
xmlns:mcc="http://standards.org/iso/19115/-3/mcc/1.0"
xmlns:mdl="http://standards.org/iso/19115/-3/mdl/1.0"
xmlns:mnl="http://standards.org/iso/19115/-3/mnl/1.0">
xmlns:lan="http://standards.org/iso/19115/-3/lan/1.0">
xmlns:lis="http://standards.org/iso/19115/-3/lis/1.0">
xmlns:gam="http://standards.org/iso/19115/-3/gam/1.0">
<mdl:metadataIdentifier>
<mcc:MD_Identifier>
<mnl:type>
<gam:String>The Metadata File</gam:String>
</mnl:type>
<mnl:description codeList="http://arcgis.com/codelist/ScopeCode" codeListValue="dataset"/>
<lan:language>
<lan:type>
<lis:name>English</lis:name>
</lan:type>
</lan:language>
</mcc:MD_Identifier>
<mcc:contactInfo>
<mdl:POC>
<mnl:name>
<lis:person>Tom</lis:person>
</mnl:name>
</mdl:POC>
</mcc:contactInfo>
</mdl:metadataIdentifier>
</nas:metadata>
【问题讨论】:
标签: python xml parsing automation lxml