XML 不使用 ElementTree 在 Python 2.7 中解析

XML Not Parsing in Python 2.7 with ElementTree

我有以下 XML 文件,我从 REST API

<?xml version="1.0" encoding="utf-8"?>
<boxes>
  <home id="1" name="productname"/>
  <server>111.111.111.111</server>
  <approved>yes</approved>
  <creation>2007 handmade</creation>
  <description>E-Commerce, buying and selling both attested</description>
  <boxtype>
      <sizes>large, medium, small</sizes>
      <vendor>Some Organization</vendor>
      <version>ANY</version>
  </boxtype>
  <method>Handmade, Handcrafted</method>
  <time>2014</time>
</boxes>

我能够得到上面的输出,存储在一个字符串变量中并在控制台打印,

但是当我将其发送到 xml ElementTree

import base64
import urllib2
from xml.dom.minidom import Node, Document, parseString
from xml.etree import ElementTree as ET
from xml.etree.ElementTree import XML, fromstring, tostring

print outputxml ##Printing xml correctly,  outputxml contains xml above
content = ET.fromstring(outputxml)
boxes = content.find('boxes')
print boxes
boxtype = boxes.find("boxes/boxtype")

如果我打印框,它会给我 None,因此会给我下面的错误

boxtype = boxes.find("boxes/boxtype")
AttributeError: 'NoneType' object has no attribute 'find'

根级节点是boxes,它在自身内部找不到boxes

boxtype = content.find("boxtype")

应该足够了。

演示:

>>> import base64
>>> import urllib2
>>> from xml.dom.minidom import Node, Document, parseString
>>> from xml.etree import ElementTree as ET
>>> from xml.etree.ElementTree import XML, fromstring, tostring
>>> 
>>> print outputxml ##Printing xml correctly,  outputxml contains xml above
<?xml version="1.0" encoding="utf-8"?>
<boxes>
  <home id="1" name="productname"/>
  <server>111.111.111.111</server>
  <approved>yes</approved>
  <creation>2007 handmade</creation>
  <description>E-Commerce, buying and selling both attested</description>
  <boxtype>
      <sizes>large, medium, small</sizes>
      <vendor>Some Organization</vendor>
      <version>ANY</version>
  </boxtype>
  <method>Handmade, Handcrafted</method>
  <time>2014</time>
</boxes>
>>> content = ET.fromstring(outputxml)
>>> boxes = content.find('boxes')
>>> print boxes
None
>>> 
>>> boxes
>>> content #note that the content is the root level node - boxes
<Element 'boxes' at 0x1075a9250> 
>>> content.find('boxtype')
<Element 'boxtype' at 0x1075a93d0>
>>>