2017-05-28 65 views
-1
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) 
+1

[xml文件的根可能的複製是給爲NONE爲什麼呢? ](https://stackoverflow.com/q/44215454/1255289) – miken32

+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) Parses an XML section into an element tree. source is a filename or file object containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an ElementTree instance.

你的代碼有兩行是no t一起使用在所有:

from xml.etree.ElementTree import ElementTree 
from xml.etree.ElementTree import Element 

而更大的問題是,它拋出一個錯誤:

AttributeError: 'str' object has no attribute 'close' 

無論在Python 2和3

因此

你似乎沒有被運行您在問題中提出的非最小示例代碼。

與w3schools.com this例如1文件/tmp/xx.xml

<?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> 
>>> 
+0

「你解析元組」是解釋問題的一種奇怪的方式。 'parse()'函數帶有一個可選的第二個參數,但該參數必須是一個'XMLParser'對象,而不是一個字符串。另外,您正在鏈接到lxml文檔,但OP沒有使用lxml。 – mzjn

+0

@mzjn我的不好,我正在看錯文檔(搜索'etree.parse()') – Anthon

+0

import xml.etree.ElementTree as etree tree = etree.parse(r'N:\ myinternwork \ files xml總線系統\ sample.xml')) root = tree.getroot() print(root) 即使現在輸出沒有任何幫助? –

相關問題