繁体   English   中英

python elementTree获取以结尾的属性

[英]python elementTree get attribute that ends with

提供以下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')

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

是否可以使用正则表达式?

另一种选择是遍历属性,并以以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”)。

如果这是一个问题,请改用regex:

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']")

下面的代码片段演示了如何从格式正确的XML文档(问题中的输入文档格式不正确)获取smpte:backgroundImage属性的值。

smpte:表示该属性已绑定到命名空间,该命名空间为http://smpte-ra.org/schemas/2052-1/2013/smpte-tt ,根据屏幕截图判断。 请注意,无论是ttmsmpte前缀必须在XML文档中声明( xmlns:ttm="..."xmlns:smpte="..."

get()调用中,必须以“ Clark表示法”给出属性名称: {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

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

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

id ='SUB6756004155_0'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM