python怎么处理xml节点包含命名空间,也就是冒号的情况
1个回答
展开全部
a:b为名不行吧,要展开为{URI}b这种形式,看看下面小例子取出的tag名称:
# -*- coding: utf-8 -*-
from xml.etree import ElementTree as ET
import cStringIO
xml = """\
<?xml version="1.0"?>
<root xmlns = "http://default-namespace.org/"
xmlns:py = "http://www.python.org/ns/">
<py:elem1 />
<elem2 xmlns="" />
</root>
"""
f = cStringIO.StringIO(xml)
#find all elements and print tag's name.
tree = ET.parse(f)
print repr(tree.getroot().tag)
elems = tree.findall('.//*')
for elem in elems:
print repr(elem.tag)
#same as above, but using iterparse.
f.seek(0)
for event, elem in ET.iterparse(f, ("start",)):
print repr(elem.tag)
输出:
'{http://default-namespace.org/}root'
'{http://www.python.org/ns/}elem1'
'elem2'
'{http://default-namespace.org/}root'
'{http://www.python.org/ns/}elem1'
'elem2'
# -*- coding: utf-8 -*-
from xml.etree import ElementTree as ET
import cStringIO
xml = """\
<?xml version="1.0"?>
<root xmlns = "http://default-namespace.org/"
xmlns:py = "http://www.python.org/ns/">
<py:elem1 />
<elem2 xmlns="" />
</root>
"""
f = cStringIO.StringIO(xml)
#find all elements and print tag's name.
tree = ET.parse(f)
print repr(tree.getroot().tag)
elems = tree.findall('.//*')
for elem in elems:
print repr(elem.tag)
#same as above, but using iterparse.
f.seek(0)
for event, elem in ET.iterparse(f, ("start",)):
print repr(elem.tag)
输出:
'{http://default-namespace.org/}root'
'{http://www.python.org/ns/}elem1'
'elem2'
'{http://default-namespace.org/}root'
'{http://www.python.org/ns/}elem1'
'elem2'
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询