【问题标题】:ElementTree find returns None?ElementTree 查找返回无?
【发布时间】:2015-06-03 15:46:25
【问题描述】:

我正在使用ElementTree 和 Python 来解析 XML 文件以查找标签 contentType 的内容。

这是 Python 行:

extensionType = ET.parse("src/" + str(filename)).find('contentType')

这是 XML:

<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
    <cacheControl>Private</cacheControl>
    <contentType>image/jpeg</contentType>
</StaticResource>

我做错了什么?

谢谢!

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    到目前为止,您只是在解析 xml 文件。这就是使用 xpath 获取元素的方法(注意如何使用给定的 xml 命名空间 xmlns

    import xml.etree.cElementTree as ET
    
    tree = ET.parse('test.xml')
    
    root = tree.getroot()
    
    xmlns = {'soap': '{http://soap.sforce.com/2006/04/metadata}'}
    ct_element = root.find('.//{soap}contentType'.format(**xmlns))
    print(ct_element.text)
    

    【讨论】:

      猜你喜欢
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多