[英]Node name from an xml file using lxml
I have an xml file with a structure like this:我有一个结构如下的 xml 文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<Validity>
<OneValidity a=1>----</OneValidity>
<OneValidity a=2>----</OneValidity>
</Validity>
<ValidityLine>
<OneValidityLinea a=1>----</OneValidityLine>
<OneValidityLinea a=2>----</OneValidityLine>
</ValidityLine>
</root>
I'd like to return, using python and lxml library, the parents node name: Validity
and ValidityLine
.我想使用 python 和 lxml 库返回父节点名称:
Validity
和ValidityLine
。
from lxml import etree
tree = etree.parse("file.xml")
root = tree.getroot()
validityLst = root.xpath('Validity')
validityLineLst = root.xpath('ValidityLine')
Found this answer years later and wanted to provide a more concise answer to what I believe OP was asking (and the question that brought me here from Google):多年后找到了这个答案,并希望为我认为 OP 提出的问题(以及让我从 Google 来到这里的问题)提供更简洁的答案:
from lxml import etree
# Parse file and get root node
tree = etree.parse("file.xml")
root = tree.getroot()
# Access root node name
name = root.tag
Note: the tag
attribute provides the name of the current node.注意:
tag
属性提供了当前节点的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.