【问题标题】:Why is my Python2 xml parser not working as expected in Python3?为什么我的 Python2 xml 解析器在 Python3 中没有按预期工作?
【发布时间】:2021-08-09 15:44:13
【问题描述】:

以下代码在 Python 2 中运行良好。

import xml.etree.ElementTree as ET
import os
import json

file_name = 'sample.xml'
full_path = os.path.join('Test', file_name)

tree = ET.parse(full_path)
myroot = tree.getroot()

for test in myroot.findall('bla/blub/test/'):
    print(test.attrib)
    for fw in test:
        print(fw.tag)
        for dn in fw.findall('name'):
            hostname =  dn.text 

如果我尝试使用 Python 3 运行代码,之后它将不会使用 for 循环:

print(fw.tag)

打印显示我在正确的位置:

{'name': 'test1'}
etc
name

任何想法,为什么代码不适用于 Python 3?

【问题讨论】:

    标签: python python-3.x python-2.7 xml.etree


    【解决方案1】:

    我找到了解决方案。我删除了第二个 for 循环。

    for test in myroot.findall('bla/blub/test/'):
        print(test.attrib)
        for dn in test.findall('name'):
            hostname =  dn.text 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2020-02-29
      • 1970-01-01
      • 2020-01-13
      • 2021-08-19
      • 2017-12-26
      相关资源
      最近更新 更多