python elementTree get属性,以

2024-04-20 09:57:12 发布

您现在位置:Python中文网/ 问答频道 /正文

将以下xml作为elementTree的输入(使用Python2.7):

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

我得到这样的属性: enter image description here

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

通常我会这样做:

^{pr2}$

但在这里我只知道属性名的一部分

可以使用regex吗?在


Tags: dividimg属性bodyxmlregionrole
3条回答

另一个选择是迭代属性并返回以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}")

输出。。。在

^{pr2}$

但这可能是脆弱的。它只返回找到的第一个属性。在

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

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

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

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

id='SUB6756004155_0'

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

smpte:表示属性绑定到一个名称空间,根据屏幕截图判断,该名称空间是http://smpte-ra.org/schemas/2052-1/2013/smpte-tt。注意,ttm和{}前缀必须在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"))

输出:

^{pr2}$

相关问题 更多 >