根据多个标签文字查找父标签

考虑我在文件中有xml的一部分,如下所示:

<Client name="Jack">
        <Type>premium</Type>
        <Usage>unlimited</Usage>
        <Payment>online</Payment>
</Client>

<Client name="Jill">
        <Type>demo</Type>
        <Usage>limited</Usage>
        <Payment>online</Payment>
</Client>

<Client name="Ross">
        <Type>premium</Type>
        <Usage>unlimited</Usage>
        <Payment>online</Payment>
</Client>


我正在使用BeautifulSoup解析值。

在这里,我需要基于标签获取客户端名称,根据标签的文本,我需要获取客户端名称。(来自父标签)。

我具有如下功能:

def get_client_for_usage(self, usage):
    """
    To get the client name for specified usage
    """
    usage_items = self.parser.findAll("client")
    client_for_usage = []
    for usages in usage_items:
        try:
            client_set = usages.find("usage", text=usage).findParent("client")
            client_attr = dict(client_set.attrs)
            client_name = client_attr[u'name']
            client_for_usage.append(client_name)

        except AttributeError:
            continue
    return client_for_usage


现在,我需要获取客户端名称,但是要基于两件事,即基于“用法”和“类型”。

因此,我需要同时传递类型和用法,以便获得客户端名称。

有人可以帮助我。如果问题不清楚,请告诉我,以便我可以根据需要进行编辑。

最佳答案

就像是

def get_client_for_usage(self, usage, tpe):
    """
    To get the client name for specified usage
    """
    usage_items = self.parser.findAll("client")
    client_for_usage = []
    for usages in usage_items:
        try:
            client_set = usages.find("usage", text=usage).findParent("client")
            typ_node = usages.find("type", text=tpe).findParent("client")
            if client_set == typ_node:
                client_for_usage.append(client_set['name'])
        except AttributeError:
            continue
    return client_for_usage

10-06 13:23
查看更多