如何使用python解析器创建适当的xml属性
我需要添加什么(属性)才能只打印addr(nmap xml文件中的ip地址)如何使用python解析器创建适当的xml属性,python,xml,parsing,Python,Xml,Parsing,我需要添加什么(属性)才能只打印addr(nmap xml文件中的ip地址) 我添加了root标记和127.0.0.1,192.168.0.1,以显示更多内容: <host starttime="1404053959" endtime="1404054014"><status state="up" reason="reset" reason_ttl="254"/> <address addr="ip" addrtype="ipv4"/> 从xml.dom.m
我添加了
root
标记和127.0.0.1
,192.168.0.1
,以显示更多内容:
<host starttime="1404053959" endtime="1404054014"><status state="up" reason="reset" reason_ttl="254"/> <address addr="ip" addrtype="ipv4"/>
从xml.dom.minidom导入解析,解析字符串
数据=“”
127.0.0.1
192.168.0.1
'''
#dom=parse('abc.xml')
dom=parseString(数据)
对于dom.getElementsByTagName(“地址”)中的节点:
打印“xml:”,node.toxml()
打印'type:',node.getAttribute('addrtype')
打印“addr:”,node.childNodes[0]。数据
结果:
from xml.dom.minidom import parse, parseString
data = '''<root>
<host starttime="1404053959" endtime="1404054014">
<status state="up" reason="reset" reason_ttl="254"/>
<address addr="ip" addrtype="ipv4">127.0.0.1</address>
</host>
<host starttime="1404053959" endtime="1404054014">
<status state="up" reason="reset" reason_ttl="254"/>
<address addr="ip" addrtype="ipv4">192.168.0.1</address>
</host>
</root>'''
#dom = parse('abc.xml')
dom = parseString(data)
for node in dom.getElementsByTagName('address'):
print ' xml:', node.toxml()
print 'type:', node.getAttribute('addrtype')
print 'addr:', node.childNodes[0].data
xml:127.0.0.1
类型:ipv4
地址:127.0.0.1
xml:192.168.0.1
类型:ipv4
地址:192.168.0.1
您需要在问题中添加部分abc.xml
文件。它是典型的nmap xml文件。它是这样的:
from xml.dom.minidom import parse, parseString
data = '''<root>
<host starttime="1404053959" endtime="1404054014">
<status state="up" reason="reset" reason_ttl="254"/>
<address addr="ip" addrtype="ipv4">127.0.0.1</address>
</host>
<host starttime="1404053959" endtime="1404054014">
<status state="up" reason="reset" reason_ttl="254"/>
<address addr="ip" addrtype="ipv4">192.168.0.1</address>
</host>
</root>'''
#dom = parse('abc.xml')
dom = parseString(data)
for node in dom.getElementsByTagName('address'):
print ' xml:', node.toxml()
print 'type:', node.getAttribute('addrtype')
print 'addr:', node.childNodes[0].data
xml: <address addr="ip" addrtype="ipv4">127.0.0.1</address>
type: ipv4
addr: 127.0.0.1
xml: <address addr="ip" addrtype="ipv4">192.168.0.1</address>
type: ipv4
addr: 192.168.0.1