英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论