我编写了一个简单的函数来解析以下xml输出的某些字段。我的意图是只解析acl字段和分配的组。但我不确定我写的函数是否是最有效的方法。
请求输出
<?xml version="1.0" encoding="UTF-8"?>
<Values version="2.0">
<array name="aclgroups" type="record" depth="1">
<record javaclass="com.wm.util.Values">
<value name="name">ACL_DEV_TEAM</value>
<Boolean name="inUse">true</Boolean>
<array name="allow" type="value" depth="1">
<value>groups_a</value>
<value>groups_b</value>
</array>
</array>
<array name="userList" type="value" depth="1">
<value>jonhn</value>
<value>bob</value>
</array>
</record>
</array>
</Values>
解析xml结果的代码
def parse_xml_list(self):
try:
acl_list = []
tree = ElementTree.fromstring(self.xml)
#Loop over all entries ( in this exemple is reduced to one only )
for records in tree.findall('./array/record'):
#Again.. loop over all records on xml
acl = records.find('value[@name="name"]').text
print(acl)
for groups in records.findall('./array[1]/value'):
print(groups.text)
print()
except Exception:
raise
finally:
self.xml = None
预期结果:
devteam
group_a
group_b
代码工作得很好,但我怎么能把它变成Pythonic?
提前感谢。