root of the xml file is giving as NONE why?

2019-03-06 03:03发布

问题:

from elementtree import ElementTree as ET
tree= ET.parse(r'N:\myinternwork\files xml of bus systems\testonieeebus.xml','r')
root= tree.getroot()
print(root)

now the error is in output as it is giving none

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<author>Giada De Laurentiis</author>
</book>
</bookstore>

回答1:

The following code is enough. You don't need to open the file at beginning. ET.parse will do it for you if you provide the correct path.

In your code you import the library as ET and then reassign the same variable by opening the file. So ET.parse() referes to your file object not to your elementtree library.

import xml.etree.ElementTree as ET

tree= ET.parse('note.xml')
root= tree.getroot()
print(root.tag) # to print root