【发布时间】:2011-11-23 20:03:48
【问题描述】:
我正在使用 etree 解析外部 xml 文件并尝试从下面的外部 xml 文件中的树中获取 listing data 并将子树 agancy 数据添加到其中。我可以分别提取isting 和agancy 的数据,但不知道如何合并它们以便listing 获得正确的agency 信息。
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>
蟒蛇:
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 合并?
【问题讨论】:
-
问题是什么?你能提供(不正确)输出和正确(期望)输出的例子吗?
-
是的,对不起。我将问题更新为更清晰,并添加了我得到的 json 输出。
-
那么,您想要的最终 XML 文档是什么?请在您的问题中提供此信息。
标签: python xml django dom xpath