我正在使用 etree 解析外部 xml 文件,并尝试从下面的外部 xml 文件中的树中获取列表数据
,并添加子树agancy
数据到它。我能够分别提取 isting
和 agancy
的数据,但不知道如何合并它们,以便 listing
得到正确的机构
信息。
xml:
<response>
<listing>
<bathrooms>2.1</bathrooms>
<bedrooms>3</bedrooms>
<agency>
<name>Bob's Realty</name>
<phone>555-693-4356</phone>
</agency>
</listing>
<listing>
<bathrooms>3.1</bathrooms>
<bedrooms>5</bedrooms>
<agency>
<name>Larry's Homes</name>
<phone>555-324-6532</phone>
</agency>
</listing>
</response>
python :
tree = lxml.etree.parse("http://www.someurl.com?random=blahblahblah")
listings = tree.xpath("/response/listing")
agencies = tree.xpath("/response/listing/agency")
listings_info = []
for listing in listings:
this_value = {
"bedrooms":listing.findtext("bedrooms"),
"bathrooms":listing.findtext("bathrooms"),
}
for agency in agencies:
this_value['agency']= agency.findtext("name")
listings_info.append(this_value)
我尝试在 listing_info.append(this_value)
发生位置上方的某个位置添加此内容,但这并不正确,只是将最后一个代理值附加到每个列表中。
我将数据输出到 json 中,如下所示(您可以看到一个机构的信息如何放入两个结果中:
{"listings":[{"agency": "Bob's Realty", "phone":"555-693-4356" "bathrooms": "2.1", "bedrooms": "3"},{"agency": "Bob's Realty", "phone":"555-693-4356" "bathrooms": "3.1", "bedrooms": "5"} ]}
如何将 response/listing/agency
中的数据与原始 for
语句中的 response/listing
合并?
最佳答案
您可以在迭代列表时使用 listing.xpath('agency/name/text()')[0]
来获取该列表的代理机构名称。
for listing in listings:
this_value = {
'bedrooms': listing.findtext('bedrooms'),
'bathrooms': listing.findtext('bathrooms'),
'agency': listing.xpath('agency/name/text()')[0]
}
listings_info.append(this_value)
关于python - 如何使用 XPATH 将子树的数据添加到 Python/Django 中的主树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532200/