2

Struggling on why lxml.objectify.parse is failing when I use a file IO but not a string IO.

The following code works:

with open(logPath,'r', encoding='utf-8') as f:
    xml = f.read()
    root = objectify.fromstring(xml)

print(root.tag)

The following code fails with error:

AttributeError: 'lxml.etree._ElementTree' object has no attribute 'tag'

with open(pelogPath,'r', encoding='utf-8') as f:
    #xml = f.read()
    root = objectify.parse(f)

print(root.tag)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
frankr6591
  • 1,211
  • 1
  • 8
  • 14

1 Answers1

2

That's because fromstring() would return a root element directly:

Parses an XML document or fragment from a string. Returns the root node (or the result returned by a parser target).

while the parse() would return an ElementTree object:

Return an ElementTree object loaded with source elements.

Use getroot() to get to the root element in this case:

tree = objectify.parse(f)
root = tree.getroot()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195