【问题标题】:python elementTree get attribute that ends withpython elementTree获取以结尾的属性
【发布时间】:2019-01-16 16:16:33
【问题描述】:

将以下 xml 作为 elementTree 的输入(使用 python 2.7):

 <body>
<div region="imageRegion" xml:id="img_SUB6756004155_0" ttm:role="caption" smpte:backgroundImage="#SUB6756004155_0">
</body>

我得到这个属性:

所以我需要找到以'backgroundImage'或'id'结尾的属性

通常我会这样做:

 div.get('region')

但是这里我只知道部分属性名,

可以使用正则表达式吗?

【问题讨论】:

标签: python xml elementtree


【解决方案1】:

另一种选择是遍历属性并返回具有以backgroundImage 结尾的本地名称的属性值。

示例...

from xml.etree import ElementTree as ET

XML = '''
<body xmlns:ttm="http://www.w3.org/ns/ttml#metadata" 
      xmlns:smpte="http://smpte-ra.org/schemas/2052-1/2013/smpte-tt">
  <div region="imageRegion" xml:id="img_SUB6756004155_0" 
       ttm:role="caption" smpte:backgroundImage="#SUB6756004155_0"></div>
</body>'''

root = ET.fromstring(XML)
div = root.find("div")
val = next((v for k, v in div.attrib.items() if k.endswith('backgroundImage')), None)

if val:
    print(f"Value: {val}")

输出...

Value: #SUB6756004155_0

不过,这可能很脆弱。它只返回找到的第一个属性。

如果这是个问题,可以使用列表来代替:

val = [v for k, v in div.attrib.items() if k.endswith('backgroundImage')]

它还会错误地返回以“backgroundImage”结尾的属性(如“invalid_backgroundImage”)。

如果这是个问题,可以改用正则表达式:

val = next((v for k, v in div.attrib.items() if re.match(r".*}backgroundImage$", "}" + k)), None)

如果你曾经能够切换到 lxml,本地名称的测试可以在 xpath 中完成...

val = div.xpath("@*[local-name()='backgroundImage']")

【讨论】:

    【解决方案2】:

    下面的 sn-p 演示了如何从格式良好的 XML 文档(问题中的输入文档格式不正确)中获取 smpte:backgroundImage 属性的值。

    smpte: 表示该属性绑定到一个命名空间,即http://smpte-ra.org/schemas/2052-1/2013/smpte-tt,从截图来看。请注意,ttmsmpte 前缀都必须在 XML 文档中声明(xmlns:ttm="..."xmlns:smpte="...")。

    get()调用中,属性名称必须在"Clark notation"中给出:{http://smpte-ra.org/schemas/2052-1/2013/smpte-tt}backgroundImage

    from xml.etree import ElementTree as ET
    
    XML = '''
    <body xmlns:ttm="http://www.w3.org/ns/ttml#metadata" 
          xmlns:smpte="http://smpte-ra.org/schemas/2052-1/2013/smpte-tt">
      <div region="imageRegion" xml:id="img_SUB6756004155_0" 
           ttm:role="caption" smpte:backgroundImage="#SUB6756004155_0"></div>
    </body>'''
    
    root = ET.fromstring(XML)
    div = root.find("div")
    print(div.get("{http://smpte-ra.org/schemas/2052-1/2013/smpte-tt}backgroundImage"))
    

    输出:

    #SUB6756004155_0
    

    【讨论】:

    • 但是这个http://smpte-ra.org/schemas/2052-1/2013/smpte-tt 可能会改变,它不是硬编码的
    【解决方案3】:

    这个解决方案也对我有用:

    r = re.compile(r'img_.+')
    image_id = filter(r.match, div.attrib.values())
    id = image_id[0].split('_', 1)[1]
    

    id ='SUB6756004155_0'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      相关资源
      最近更新 更多