【问题标题】:How to retrieve the parent node using cElementTree?如何使用 cElementTree 检索父节点?
【发布时间】:2010-09-27 07:37:37
【问题描述】:

对于 xml

<grandparent>
  <parent1>
     <child>data1</child>
  </parent1>
  <parent2>
     <child>data2</child>
  </parent2>
</grandparent>

我需要包含父级元组的列表,xml 中每个父级的数据。

有没有办法使用 cElementTree 做到这一点?我可以为孩子、数据做这件事,但不幸的是孩子在所有值上都是相同的,因此它没有多大用处。

【问题讨论】:

    标签: python celementtree


    【解决方案1】:

    您似乎可以使用 ElementTree 1.3 版(检查http://effbot.org/zone/element-xpath.htm)通过使用 xpath 命令(如child.find('../parent'))从子级访问父级。但我认为 python 附带版本 1.2 或其他版本。

    您还应该检查与 etree 兼容并具有完整 Xpath 支持的 lxml http://lxml.de/

    【讨论】:

    • 文档在docs.python.org/2/library/xml.etree.elementtree 中说类似Changed in version 2.7: The ElementTree API is updated to 1.3. 的内容我使用的是2.7,但对我来说'../myparent' 似乎仍然不起作用;这是什么意思?
    • 是的,我认为这不是 cElementTree 中的支持。例如:ET.fromstring("").find('.//b').find('..') 返回无
    • @AndySmith 我想我知道为什么它没有返回。 doc saysSelects the parent element. Returns None if the path attempts to reach the ancestors of the start element (**the element find was called on**).
    【解决方案2】:
    parent_map = dict((c, p) for p in tree.getiterator() for c in p)
    parent_map[el].remove(el)
    

    【讨论】:

    • +1。因为在 elementTree 中,通过.. 访问父级已损坏或无法正常工作或我不知道的任何其他方式。所以您的方式将解决它!我们也可以使用{c:p for p in tree.getiterator() for c in p}
    • @namit 我可以确认这一点。我可以正确访问我的节点,但是当我这样做时 print('parent = ', el.findall("../")) 这就是 this 所说的那样,我得到空对象。
    • @namit 原来我没有正确阅读.. 的文档:Selects the parent element. Returns None if the path attempts to reach the ancestors of the start element (the element find was called on).link
    【解决方案3】:

    这种语法似乎适用于 cElementTree

    ET.fromstring("<c><a><b></b></a></c>").find('.//b/..')
    

    不去基父,在路径中使用双斜杠然后单斜杠。
    (会作为评论发布到上述线程,但似乎我没有特权)

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多