2010-08-07 68 views
3

如何訪問XML樹的根元素處的多個xmlns聲明?例如:XML和Python:獲取在根元素中聲明的名稱空間

import xml.etree.cElementTree as ET 
data = """<root 
      xmlns:one="http://www.first.uri/here/" 
      xmlns:two="http://www.second.uri/here/"> 

      ...all other child elements here... 
      </root>""" 

tree = ET.fromstring(data) 
# I don't know what to do here afterwards 

我想要得到的字典與此類似,或至少一些格式,使之更容易得到URI和匹配的標籤

{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"} 

回答

2

我不知道如何用xml.etree完成,但用lxml.etree可以這樣做:

import lxml.etree as le 
data = """<root 
      xmlns:one="http://www.first.uri/here/" 
      xmlns:two="http://www.second.uri/here/"> 

      ...all other child elements here... 
      </root>""" 

tree = le.XML(data) 
print(tree.nsmap) 
# {'two': 'http://www.second.uri/here/', 'one': 'http://www.first.uri/here/'} 
相關問題