【问题标题】:Return a parent tag attribute from selected child从所选子项返回父标记属性
【发布时间】:2015-09-05 12:56:00
【问题描述】:
<TAGS>    
  <PARENT ID="Parent Id">
     <MID>
      <CHILD ATTR="Child Value"

我有一段代码正在为某些 xml 选择与“子值”相对应的所有属性值。

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

我的代码当前定位并检索子值,但我无法从父 ID 获取值。正确的语法是什么?

目前的代码是这样的:

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

我想检索,在本例中是父 ID 值,因为选择了孩子。

【问题讨论】:

    标签: python xml xml-parsing beautifulsoup


    【解决方案1】:

    有相关的find_parent() method

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

    【讨论】:

      【解决方案2】:

      由于标签的原因,我假设您使用的是 python 和 beautifulsoup。如果有,有哪些版本?

      有一个.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)
      

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2010-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-08
        • 2019-01-07
        相关资源
        最近更新 更多