2017-03-23 1 views
0

私が持っていれば、このようなXMLファイル:ElementTreeを持つXML文書の名前空間定義をリストしますか?

<root 
xmlns:a="http://example.com/a" 
xmlns:b="http://example.com/b" 
xmlns:c="http://example.com/c" 
xmlns="http://example.com/base"> 
    ... 
</root> 

どのように私は名前空間の定義のリスト(すなわち、xmlns:a="…"、など)を得ることができますか?使用

import xml.etree.ElementTree as ET 

tree = ET.parse('foo.xml') 
root = tree.getroot() 
print root.attrib() 

は、空の属性辞書を表示します。

+0

ここでは、ElementTreeので行うことができる方法であります:http://stackoverflow.com/a/42372404/407651 – mzjn

答えて

1

lxmlの方が使いやすいかもしれません。

from lxml import etree 
xml_data = '<root xmlns:a="http://example.com/a" xmlns:b="http://example.com/b" xmlns:c="http://example.com/c" xmlns="http://example.com/base"></root>' 

root_node = etree.fromstring(xml_data) 
print root_node.nsmap 

これは@mzjn経由

{None: 'http://example.com/base', 
'a': 'http://example.com/a', 
'b': 'http://example.com/b', 
'c': 'http://example.com/c'} 
0

を出力し、コメントで、ここでは株式のElementTreeでそれを行う方法は次のとおりです。https://stackoverflow.com/a/42372404/407651

import xml.etree.ElementTree as ET 
my_namespaces = dict([ 
    node for (_, node) in ET.iterparse('file.xml', events=['start-ns']) 
]) 
関連する問題