你没有解析文件sample.xml,因为你提供的第二个参数('r'),如果你这样做了例如:
tree= etree.parse(open(r'N:\myinternwork\files xml of bus systems\sample.xml','r'))
或
tree= etree.parse(r'N:\myinternwork\files xml of bus systems\sample.xml')
根据the xml doc:
xml.etree.ElementTree.parse(source, parser=None)
将 XML 部分解析为元素树。 source 是包含 XML 数据的文件名或文件对象。 parser 是一个可选的解析器实例。如果未给出,则使用标准 XMLParser 解析器。返回一个 ElementTree 实例。
您的代码有两行根本没有使用:
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
更大的问题是它会抛出错误:
AttributeError: 'str' object has no attribute 'close'
在 Python 2 和 3 上
因此,您似乎没有运行您在问题中提供的非最小示例代码。
在文件/tmp/xx.xml 中使用来自 w3schools.com 的 this 示例 1:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
我可以交互地运行它:
$ python
Python 3.6.1 (default, Mar 22 2017, 11:20:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as etree
>>> tree = etree.parse('/tmp/xx.xml')
>>> print(tree)
<xml.etree.ElementTree.ElementTree object at 0x7ff247570e10>
>>> root = tree.getroot()
>>> print(root)
<Element 'note' at 0x7ff24756d7c8>
>>>