python xml解析期间的NameError
问题描述:
>>> 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
答
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
答
好像你是缺少导入!
从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!
后的完整代码 –