我正在尝试使用 lxml 使用 python 解析 XML 文件,但在基本尝试中遇到错误。我用 this post和 the lxml tutorials Bootstrap 。
我的 XML 文件基本上是根据以下记录构建的(我对其进行了删减以便于阅读):
<?xml version="1.0" ?>
<?xml-stylesheet href="file:///usr/share/nmap/nmap.xsl" type="text/xsl"?>
<nmaprun scanner="nmap" args="nmap -sV -p135,12345 -oX 10.232.0.0.16.xml 10.232.0.0/16" start="1340201347" startstr="Wed Jun 20 16:09:07 2012" version="5.21" xmloutputversion="1.03">
<host>
<hostnames>
<hostname name="host1.example.com" type="PTR"/>
</hostnames>
</host>
</nmaprun>
我通过这个复杂的脚本来运行它:
from lxml import etree
d = etree.parse("myfile.xml")
for host in d.findall("host"):
aa = host.find("hostnames/hostname")
print aa.attrib["name"]
我在 print
行收到 AttributeError: 'NoneType' object has no attribute 'attrib'
。
我检查了d
、host
和aa
的值,它们都被定义为元素。
如果这是显而易见的事情(很可能是这样),请先致歉。
编辑:我按要求添加了 XML 文件的标题(我仍在阅读和重读答案:))
谢谢!
最佳答案
您可以使用 xpath 表达式解决此问题。
d.xpath('//hostname/@name') # thank you for comment
或者
for host in d.xpath('//hostname'):
print host.get('name'), host.get('whatever else etc...')
关于python:基本 XML 解析错误(使用 lxml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11123536/