我使用minidom解析xml文件(我尝试了Element Tree,但是我发现更容易执行minidom的操作;现在可能证明我做错了:))
让我们说我的xml如下:
<country name="UK" area = "Europe">
<city name = "London">Text1</city>
<city name = "Birmingham">Text2</city>
</country>
<country name="US" area = "America">
<city name = "Washington">Text3</city>
<city name = "New York">Text4</city>
</country>
我希望能够创建一个嵌套列表,如下所示:
[['London','Birmingham'],['Washington','New York']]
我能够解析并获得以下列表:
['London','Birmingham','Washington','New York']
,但不是按国家/地区分类。有谁知道如何做到这一点?
[编辑]:这是我的代码:
country = doc.getElementsByTagName("country")
city = doc.getElementsByTagName("city")
for c in country :
c_list.append(c)
index = 0
for c in country:
index = country.index(c)
for ci in city:
if ci.getAttribute('name') != "":
city_list[index].append(ci.getAttribute('name'))
index += 1