简体   繁体   中英

Node name from an xml file using lxml

I have an xml file with a structure like this:

<?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 .

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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM