2017-07-03 48 views
0
>>> stringx 
'<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>' 
>>> 
>>> 
>>> e = xml.etree.ElementTree.fromstring(stringx) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'xml' is not defined 

有人可以建議我在這裏錯過了什麼嗎?是它的XML代碼或我想解析的方式?python xml解析期間的NameError

+2

後的完整代碼 –

回答

1

import xml.etree.ElementTree

看起來你已經忘記了這一點。

參考文檔以瞭解正確的用法。

https://docs.python.org/2/library/xml.etree.elementtree.html

編輯:感謝@mzjn。你是對的。我剛剛路過,並注意到OP忘記了導入。沒有真正嘗試過。信貸去找你:)

+0

只需添加'進口xml'將無法正常工作。您必須執行'import xml.etree.ElementTree'以便在代碼中使用'xml.etree.ElementTree.fromstring()'。 – mzjn

-1

好像你是缺少導入!

從xml.etree進口ElementTree的

stringx='<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>' 

e = ElementTree.fromstring(stringx) #will wok fine!