试图找到更好的方法在Python中导航XML文件。现在有这样的东西
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
TagSlug = '{http://www.aec.gov.au/xml/schema/mediafeed}'
for child in root:
DID = child.find('PollingDistrictIdentifier')
for grandchild in child.getchildren():
Name = grandchild.find('TagSlug+Name')
for grandgrandchild in grandchild.getchildren():
for grandgrandgrandchild in grandgrandchild.getchildren():
PP = grandgrandchild.find(TagSlug+'PollingPlaceIdentifier')
print(PP.attrib['Id'], PP.attrib['Name'], DID.attrib['Id'], Name.text)
XML的结构与下面的类似
<PollingDistrictList Created="2018-10-30T12:01:21.043" xmlns="http://www.aec.gov.au/xml/schema/mediafeed" xmlns:eml="urn:oasis:names:tc:evs:schema:eml" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" xmlns:xnl="urn:oasis:names:tc:ciq:xsdschema:xNL:2.0" xmlns:ts="urn:oasis:names:tc:evs:schema:eml:ts" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
<TransactionId>4C59F7F3-2405-4443-8A1F-3F2BEF6E07C4</TransactionId>
<eml:EventIdentifier Id="12122">
<eml:EventName>State Election 2018</eml:EventName>
</eml:EventIdentifier>
<PollingDistrict>
<PollingDistrictIdentifier Id="10153">
<Name>Albert Park District</Name>
</PollingDistrictIdentifier>
<PollingPlaces>
<PollingPlace>
<PollingPlaceIdentifier Id="13133" Name="Bridport" />
<WheelchairAccess>None</WheelchairAccess>
</PollingPlace>
<PollingPlace>
<PollingPlaceIdentifier Id="13987" Name="Kerferd South" />
<WheelchairAccess>None</WheelchairAccess>
</PollingPlace>
<PollingPlaceIdentifier Id="13504" Name="Middle Park" />
<WheelchairAccess>None</WheelchairAccess>
</PollingPlace>
</PollingDistrict>
<PollingDistrict>
<PollingDistrictIdentifier = ....
et cetera
我正试图打印一份投票点ID、投票地点名称、地区ID和地区名称的列表,但最后一部分很难完成。我试过几种不同的方法,以下是一些方法:
a = tree.findall('./PollingDistrictList/PollingDistrict/PollingPlaces/PollingPlace')
print(a.text)
a = tree.findall('.//PollingPlace')
print(a.text)
我最终得到的错误是'Nonetype'或'list'没有属性'text',如果我删除了'.text',我什么也得不到。我希望找到一种更好的方法来导航XML文件,而不是做这种递归的“根中的子对象”的工作
理想情况下,我会得到:
[PP1Id], [PP1Name], [District1Id], [District1Name]
[PP2Id], [PP2Name], [District1Id], [District1Name]
...
[PP1Id], [PP1Name], [District2Id], [District2Name]
etc
如有任何建议,将不胜感激
修复了以下问题。这样你就可以看到它在做什么
相关问题 更多 >
编程相关推荐