获取XML ElementTree中的父元素

huangapple go评论65阅读模式
英文:

Get Parent XML Element with XML ElementTree

问题

Sure, here are the translations for the requested content:

有没有一种顺畅的方式来访问元素的父元素

例如:

<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>

对于<B>,我想获取<A>,对于<Z><C>,和<D>,我想获取<B>

英文:

Is there a smooth way to access the parent element of an element

For example:

<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>

For <B> I want to get <A> and for <Z>, <C>, <D> I want to get <B>

答案1

得分: 0

你可以尝试使用XPath缩写语法 ..

这将类似于:

.//B/..

(它以 . 开头,因为ElementTree不允许在元素上使用绝对路径。)

示例:

import xml.etree.ElementTree as ET

xml = """
<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>
"""

root = ET.fromstring(xml)

for elem_name in ['B', 'Z']:
    # 示例xpath:.//Z/..
    print(f"{elem_name}的父级" + root.find(f".//{elem_name}/..").tag)

这将打印:

B的父级:A
Z的父级:B

如果你可以使用lxml,它具有方便的 getparent() 方法(以及完整的xpath 1.0支持和对exslt扩展的支持)。

英文:

You could try using the XPath abbreviated syntax ...

This would be something like:

.//B/..

(It starts with . because ElementTree doesn't allow an absolute path on an element.)

Example:

import xml.etree.ElementTree as ET

xml = """
<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>
"""

root = ET.fromstring(xml)

for elem_name in ['B', 'Z']:
    # Example xpath: .//Z/..
    print(f"Parent of '{elem_name}': " + root.find(f".//{elem_name}/..").tag)

This prints:

Parent of 'B': A
Parent of 'Z': B

If you could use lxml, it has the handy method getparent() (plus full xpath 1.0 support and support of exslt extensions).

huangapple
  • 本文由 发表于 2023年4月13日 20:24:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定