intertext()只取1个位置参数(给定2个)

时间:2013-03-25 18:33:25

标签: python xml

不完全确定如何处理此错误...

代码:

import xml.etree.ElementTree as ET
tree = ET.parse('network_objects.xml')
root = tree.getroot()

for network in root.iterfind('network_object'):
    name = network.find('Name')
    class_name = network.find('Class_Name')
    color = network.find('color')
    for netmaskElement in network.iterfind('netmask'):
        netmask = network.itertext('netmask')    
    for ipaddyElement in network.iterfind('ipaddr'):
        ipaddy = network.find('ipaddr')
    print (name.text,class_name.text,ipaddy.text,netmask,color.text)

错误:

builtins.TypeError: itertext() takes exactly 1 positional argument (2 given)
line 10, in <module>
netmask = network.itertext('netmask')

XML本身,作为一个例子:

<network_objects>
<network_object>
<Name>Internal-192.168.112.0_24b</Name>
<Class_Name>network</Class_Name>
<add_adtr_rule>false</add_adtr_rule>
<broadcast><![CDATA[allow]]></broadcast>
<color><![CDATA[dark orchid]]></color>
<comments><![CDATA[no comment]]></comments>
<edges/>
<ipaddr><![CDATA[192.168.112.0]]></ipaddr>
<location><![CDATA[internal]]></location>
<location_desc><![CDATA[]]></location_desc>
<netmask><![CDATA[255.255.255.0]]></netmask>
<type><![CDATA[network]]></type>
</network_object>
</network_objects>

当然其他对象包含网络掩码,我假设是错误的来源,但是我认为for循环会纠正错误。

我该如何解决这个问题? :)

2 个答案:

答案 0 :(得分:2)

itertext( 'netmask')更改为itertext()

文档显示它没有像您当前那样接收其他参数。

itertext documentation

答案 1 :(得分:0)

为什么不在循环的其余部分使用.find?

import xml.etree.ElementTree as ET
tree = ET.parse('network_objects.xml')
root = tree.getroot()

for network in root.iterfind('network_object'):
    name = network.find('Name')
    class_name = network.find('Class_Name')
    color = network.find('color')
    for netmaskElement in network.iterfind('netmask'):
        netmask = network.find('netmask')    
    for ipaddyElement in network.iterfind('ipaddr'):
        ipaddy = network.find('ipaddr')
    print (name.text,class_name.text,ipaddy.text,netmask,color.text)