Python xml.etree.ElementTree问题

时间:2018-11-02 01:15:02

标签: python xml

从不介意-我发现了我的真实问题,这是我所实现的代码中的进一步内容。

我在使xml.etree.ElementTree正常工作方面遇到问题。

xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><suggestedmatches><destination><sortOrder>1</sortOrder><destinationType>destinationType1</destinationType></destination><destination><sortOrder>2</sortOrder><destinationType>destinationType2</destinationType></destination></suggestedmatches>"
root = ET.fromstring(xmlData)
logging.debug("DIAG: %s: root.tag = %s"
  % (FUNCTION_NAME, root.tag))
logging.debug("DIAG: %s: root = %r" % (FUNCTION_NAME, ET.tostring(root)))
destinations = root.findall("destination")
logging.debug('DIAG: %s: destinations = %r' % (FUNCTION_NAME, ET.tostring(destinations)))

我试图弄清楚为什么在destinations中找不到root

DEBUG:root:DIAG: findDestinations(): root.tag = suggestedmatches
DEBUG:root:DIAG: findDestinations(): root = b'<suggestedmatches><destination><sortOrder>1</sortOrder><destinationType>destinationType1</destinationType></destination><destination><sortOrder>2</sortOrder><destinationType>destinationType2</destinationType></destination></suggestedmatches>'
ERROR:root:findDestinations(): Encountered exception on root.findall() - 'list' object has no attribute 'iter'

如果我在获得root之后添加以下代码,我会在日志中看到每个目的地:

for destination in root:
  destinationList.append(destination)
  logging.debug('DIAG: %s: destination.tag = %s'
    % (FUNCTION_NAME, destination.tag))

相同的代码在不同的脚本中运行,所以我不确定为什么它在这里不起作用。

1 个答案:

答案 0 :(得分:1)

您得到None是因为ET.dump写入sys.stdout,并且您正在记录dump的返回None

来自docs

  

xml.etree.ElementTree.dump(elem)

     

将元素树或元素结构写入sys.stdout。此功能应仅用于调试。

     

确切的输出格式取决于实现。在此版本中,它是作为普通XML文件编写的。

     

elem是元素树或单个元素。

尝试使用tostring方法代替dump

logging.debug("DIAG: %s: root = %r" % (FUNCTION_NAME, ET.tostring(root)))
相关问题