在Python/Djang中,如何使用XPATH将子树的数据添加到主树中

2024-09-27 00:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用etree解析一个外部xml文件,并尝试从下面的外部xml文件中获取树中的listing data,并将子树agancy数据添加到其中。我可以分别提取istingagancy的数据,但不知道如何合并它们,以便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>

Python:

^{pr2}$

我尝试在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"} ]}

如何在原始的for语句中合并来自response/listing/agency和{}的数据?在


Tags: 文件数据name信息responsephonexmlbob
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:30

您可以在遍历列表时使用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)

相关问题 更多 >

    热门问题