Skip to main content
 首页 » 编程设计

python之我想使用 lxml 删除花括号和 XML 命名空间,只报告标签名称

2025年05月04日10davidwang456

所以我有以下 XML 文档 它更长:

<?xml version ="1.0" encoding="UTF-8" standalone="no" ?> 
<!DOCTYPE fmresultset PUBLIC "-//FMI//DTD fmresultset//EN" "http://localhost:16020/fmi/xml/fmresultset.dtd"> 
<fmresultset xmlns="http://www.filemaker.com/xml/fmresultset" version="1.0"> 
<error code="0"> 
</error> 
<product build="11/11/2014" name="FileMaker Web Publishing Engine" version="13.0.5.518"> 
</product> 

我使用以下 python 提取一些标签名称:

doc = etree.fromstring(resulttxt) 
print( doc.attrib) 
print(doc.tag) 
print(doc[4][0][0].tag) 
if(doc[4][0][0].tag == 'field'): 
    print 'hi' 

不过我得到的是:

{'version': '1.0'} 
{http://www.filemaker.com/xml/fmresultset}fmresultset 
{http://www.filemaker.com/xml/fmresultset}field 

xmlns 没有显示为根标记的属性,但它在那里。

并且它被放置在每个标签名称的前面,这使得循环和使用条件变得困难。我希望 doc.tag 只显示标签而不是命名空间和标签。

这是我使用它的第一天。有人可以帮忙吗?

请您参考如下方法:

您需要处理namespaces ,在你的例子中是一个 empty one :

from lxml import etree as ET 
 
data = """<?xml version ="1.0" encoding="UTF-8" standalone="no" ?> 
<!DOCTYPE fmresultset PUBLIC "-//FMI//DTD fmresultset//EN" "http://localhost:16020/fmi/xml/fmresultset.dtd"> 
<fmresultset xmlns="http://www.filemaker.com/xml/fmresultset" version="1.0"> 
    <error code="0"> 
    </error> 
    <product build="11/11/2014" name="FileMaker Web Publishing Engine" version="13.0.5.518"> 
    </product> 
</fmresultset> 
""" 
 
namespaces = { 
  "myns": "http://www.filemaker.com/xml/fmresultset" 
} 
 
tree = ET.fromstring(data) 
print tree.find("myns:product", namespaces=namespaces).attrib.get("name") 

打印:

FileMaker Web Publishing Engine