如何使用python解析器创建适当的xml属性

时间:2014-07-02 13:22:00

标签: python xml parsing

from xml.dom.minidom import parse

dom = parse('abc.xml')

for node in dom.getElementsBy('addr'): 
    print node.toxml()  

我需要添加什么(属性)才能只打印地址(来自nmap xml文件的IP地址)?

<host starttime="1404053959" endtime="1404054014"><status state="up" reason="reset" reason_ttl="254"/> <address addr="ip" addrtype="ipv4"/>

1 个答案:

答案 0 :(得分:0)

我添加root代码和127.0.0.1192.168.0.1以显示更多内容:

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