对于这个 XML
<Departments orgID="123" name="xmllist">
<Department>
<orgID>124</orgID>
<name>A</name>
<type>type a</type>
<status>Active</status>
<Department>
<orgID>125</orgID>
<name>B</name>
<type>type b</type>
<status>Active</status>
<Department>
<orgID>126</orgID>
<name>C</name>
<type>type c</type>
<status>Active</status>
</Department>
</Department>
</Department>
<Department>
<orgID>109449</orgID>
<name>D</name>
<type>type d</type>
<status>Active</status>
</Department>
</Departments>
如何使用Python的lxml
etree
获取节点的所有父节点。
期望输出:输入orgid=126,将返回所有父节点,例如:
{'A':124,'B':125,'C':126}
print
语句之前,将for depts in target.xpath('ancestor-or-self::Departments'): d[depts.get('name')] = depts.get('orgID')
添加到代码中。 - falsetrudict
本身是无序的数据结构。如果您想保持顺序,请使用collection.OrderedDict
。或者,如果您不需要使用类似字典的容器,则可以使用list
... - falsetru