从所选子项返回父标记属性

时间:2022-11-27 18:22:51
<TAGS>    
  <PARENT ID="Parent Id">
     <MID>
      <CHILD ATTR="Child Value"

I have a piece of code which is selecting all the attribute values for some xml that correspond to "Child Value".

我有一段代码,它选择对应于“Child Value”的某些xml的所有属性值。

I also need to have the "Parent Value", to relate the two items, for future use.

我还需要有“父母价值”来关联这两个项目,以备将来使用。

My code currently locates and retrieves the child values, but I'm having difficulty getting the value from the Parent ID. What would be the correct syntax for this?

我的代码当前找到并检索子值,但是我很难从父ID中获取值。这个的正确语法是什么?

Currently the code is similar to this:

目前代码与此类似:

taglist = []
for parent in soup.find_all('tags'):
    for each in parent.find_all('child'):
        taglist.append(repr(each['attr']))

I want to retrieve, in this example the PARENT ID value, as the child is selected.

我希望在选择子项时,在此示例中检索PARENT ID值。

2 个解决方案

#1


0  

There is the relevant find_parent() method:

有相关的find_parent()方法:

child.find_parent("parent", id=True)["id"]

#2


0  

because of the tags I'm assuming you are using python and beautifulsoup. If so, which versions?

因为标签我假设你正在使用python和beautifulsoup。如果是这样,哪个版本?

There is a .parent that can be used like in:

有一个.parent可以像以下一样使用:

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parents

child=soup.find("child", {"attr" : "value"})
for parent in child.parents:
    if parent.get('id')) == "Parent Id":
        print(parent)

#1


0  

There is the relevant find_parent() method:

有相关的find_parent()方法:

child.find_parent("parent", id=True)["id"]

#2


0  

because of the tags I'm assuming you are using python and beautifulsoup. If so, which versions?

因为标签我假设你正在使用python和beautifulsoup。如果是这样,哪个版本?

There is a .parent that can be used like in:

有一个.parent可以像以下一样使用:

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parents

child=soup.find("child", {"attr" : "value"})
for parent in child.parents:
    if parent.get('id')) == "Parent Id":
        print(parent)