繁体   English   中英

使用lxml从xml中提取嵌套名称空间

[英]Extracting nested namespace from a xml using lxml

我是Python的新手,目前正在学习解析XML。 直到我碰到嵌套名称空间的墙,一切似乎都进行得很好。

以下是我的xml的代码段(包含我要解析的开始和子元素:

<?xml version="1.0" encoding="UTF-8"?>
-<CompositionPlaylist xmlns="http://www.digicine.com/PROTO-ASDCP-CPL-20040511#">
<!-- Generated by orca_wrapping version 3.8.3-0 -->
<Id>urn:uuid:e0e43007-ca9b-4ed8-97b9-3ac9b272be7a</Id>
-------------
-------------
------------- 
-<cc-cpl:MainClosedCaption xmlns:cc-cpl="http://www.digicine.com/PROTO- ASDCP-CC-CPL-20070926#"><Id>urn:uuid:0607e57f-edcc-46ec- 997a-d2fbc0c1ea3a</Id><EditRate>24 1</EditRate><IntrinsicDuration>2698</IntrinsicDuration></cc-cpl:MainClosedCaption>
------------
------------
------------
</CompositionPlaylist>

我需要的是一种提取本地名称“ MainClosedCaption”的URI的解决方案。 在这种情况下,我尝试提取字符串“ http://www.digicine.com/PROTO- ASDCP-CC-CPL-20070926#”。 我浏览了很多教程,但似乎找不到解决方案。

如果有任何人可以借用您的专业知识,将不胜感激。

到目前为止,我在两位贡献者的帮助下所做的工作:

#!/usr/bin/env python

from xml.etree import ElementTree as ET #import ElementTree module as an alias ET
from lxml import objectify, etree

def parse():

import os
import sys
cpl_file = sys.argv[1]
xml_file = os.path.abspath(__file__)
xml_file = os.path.dirname(xml_file)
xml_file = os.path.join(xml_file,cpl_file)

with open(xml_file)as f:
    xml = f.read()

tree = etree.XML(xml)

caption_namespace = etree.QName(tree.find('.//{*}MainClosedCaption')).namespace

print caption_namespace
print tree.nsmap

nsmap = {}

for ns in tree.xpath('//namespace::*'):
    if ns[0]:
        nsmap[ns[0]] = ns[1]
tree.xpath('//cc-cpl:MainClosedCaption', namespace=nsmap)

return nsmap


if __name__=="__main__":

parse()

但是到目前为止,它还没有奏效。 当我使用QName定位标签及其名称空间时,得到的结果为“ None”。 当我尝试按照另一篇文章中的建议使用for循环在XML中定位所有名称空间时,出现错误“未知返回类型:dict”

有什么建议吗?

该程序将显示指示标签的名称空间:

from lxml import etree

xml = etree.XML('''<?xml version="1.0" encoding="UTF-8"?>
<CompositionPlaylist xmlns="http://www.digicine.com/PROTO-ASDCP-CPL-20040511#">
<!-- Generated by orca_wrapping version 3.8.3-0 -->
<Id>urn:uuid:e0e43007-ca9b-4ed8-97b9-3ac9b272be7a</Id>
<cc-cpl:MainClosedCaption xmlns:cc-cpl="http://www.digicine.com/PROTO-ASDCP-CC-CPL-20070926#">
<Id>urn:uuid:0607e57f-edcc-46ec- 997a-d2fbc0c1ea3a</Id>
<EditRate>24 1</EditRate>
<IntrinsicDuration>2698</IntrinsicDuration>
</cc-cpl:MainClosedCaption>
</CompositionPlaylist>
''')

print etree.QName(xml.find('.//{*}MainClosedCaption')).namespace

结果:

http://www.digicine.com/PROTO-ASDCP-CC-CPL-20070926#

参考: http : //lxml.de/tutorial.html#namespaces

暂无
暂无

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

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