我想要获取 XML 文档的第一个子级(不知道节点的确切名称),多层次。
我正在将一些代码从 JS 移植到 Python。这是 JS 代码:
let document = XmlService.parse(response);
let root = document.getRootElement();
return root.getContent(0).getContent(0).getContent(0).getContent(0);
我在Python中使用ElementTree,我现在有这个:
tree = ElementTree(fromstring(response.text))
root = tree.getroot()
print(list(root.iter())[0].tag)
这样就得到了第一个元素的标签,good。 但当我尝试更深入时,就像这样:
print(list(list(root.iter())[0].iter())[0].tag)
相当丑陋的代码,但是这一行产生的结果与前一行相同。显示第 1 级第一个元素的标签,而不是第 2 级第一个元素的标签。
非常感谢任何帮助或指导。
要在不知道节点的确切名称的情况下使用 Python 中的 ElementTree 库获取 XML 文档的第一个子元素,您可以递归地迭代根元素的子元素,直到达到所需的深度。具体方法如下:
import xml.etree.ElementTree as ET
def get_first_child(root, depth=1):
if depth == 1:
# If depth is 1, return the tag of the first child of the root element
return root[0].tag
else:
# If depth is greater than 1, recursively call the function on the first child
return get_first_child(root[0], depth - 1)
# Parse the XML response
tree = ET.ElementTree(ET.fromstring(response.text))
root = tree.getroot()
# Call the function to get the tag of the first child at a specific depth
first_child_tag = get_first_child(root, depth=2)
print(first_child_tag)