from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as etree
tree= etree.parse(r'N:\myinternwork\files xml of bus systems\sample.xml','r')
root= tree.getroot()
print(root)
答案 0 :(得分:1)
你没有解析文件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>
>>>