【问题标题】:Recursively parse all xml files and exclude folder递归解析所有xml文件并排除文件夹
【发布时间】:2017-02-13 20:02:08
【问题描述】:

我正在尝试解析给定文件夹/子文件夹中的所有 XML 文件,并搜索和替换该 XML 中的文本。同时排除子文件夹“存档”。我收到错误“AttributeError: 'NoneType' object has no attribute 'replace'”不确定我缺少什么,但是一旦到达 ElementTree 打开并解析 XML,我的循环似乎就死了。

for roots, dirs, files in os.walk("C:\test", topdown=True):
    if 'Archive' in dirs:
        dirs.remove('Archive')
    #dirs[:] = [d for d in dirs if 'Archive' not in d]
    for f in files:
        if f.endswith('.xml'):
            try:
                with open(os.path.join(roots, f), 'r') as xml:
                  tree = ET.parse(xml)
                  root = tree.getroot()

                  for elem in root.getiterator():
                    try:
                      print (elem.text)
                      elem.text = elem.text.replace('_THUMBNAIL.jpg', '.mxd.jpg')

                    except ET.ParseError:
                        pass

                tree.write(xml, encoding='utf-8')
            except FileNotFoundError:
                pass

【问题讨论】:

    标签: python xml lxml elementtree


    【解决方案1】:

    我猜不是所有的 XML 标记都有文本。所以你应该使用

    if elem.text is not None :
        try:
            print (elem.text)
            elem.text = elem.text.replace('_THUMBNAIL.jpg', '.mxd.jpg')
    

    【讨论】:

    • 嗯,没有骰子。它似乎跳过了所有内容。
    • 你能显示你的 xml 的一小部分吗?看起来很奇怪。
    猜你喜欢
    • 2012-11-19
    • 2011-01-12
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多