2012-01-24 118 views
3

我想在xml文件中打印所有的元素和屬性。這個xml文件的內容是:如何使用Python解析XML文件?

<topology> 
<switch id="10"> 
    <port no="1">h1</port> 
    <port no="2">h2</port> 
</switch> 

<tunnel id="91"> 
<port no="1">s1</port> 
<port no="8">s8</port> 
</tunnel> 
</topology> 

我該怎麼做?另外,我該如何搜索內部拓撲結構之類的元素?

+1

步驟1搜索。 Python在標準庫中已經有了幾個XML解析器。 http://docs.python.org/library/markup.html標準庫文檔的哪些部分很難閱讀?請選擇一個現有的XML解析器,並按照示例進行操作。當你陷入困境時,請詢問關於你選擇的解析器的**特定**問題。 –

+0

這是一個棘手的問題。有幾個。他們有不同的目的。我已經全部使用了它們。請在提出愚蠢的問題之前先閱讀**文檔。 –

+1

請查看此[鏈接](http://www.blog.pythonlibrary.org/2010/11/12/python-parsing-xml-with-minidom/)。它應該簡單明瞭。 – Frankline

回答

4

像美國洛特表示,你有太多的方法對皮膚這隻貓,

這裏是用一個例子 lxml

from lxml import etree 

xml_snippet = '''<topology> 
<switch id="10"> 
    <port no="1">h1</port> 
    <port no="2">h2</port> 
</switch> 

<tunnel dpid="91"> 
<port no="1">s1</port> 
<port no="8">s8</port> 
</tunnel> 
</topology>''' 

root = etree.fromstring(xml_snippet) 

for element in root.iter("*"): 
    print element.tag, element.items() 

輸出:

topology [] 
switch [('id', '10')] 
port [('no', '1')] 
port [('no', '2')] 
tunnel [('dpid', '91')] 
port [('no', '1')] 
port [('no', '8')] 

使用XPath查找屬性

attribute = '10' 
element = root.find('.//switch[@id="%s"]' % attribute) 
element.items() 

輸出:

[('id', '10')] 
4

這是我工作的代碼:

import xml.etree.ElementTree as ET 

doc = ET.parse("nm.xml") 
s = doc.find("switch") 
print s.attrib["id"] 
for item in s: 
    print item.attrib["no"] 
    print item.text 

t = doc.find("tunnel") 
print t.attrib["dpid"] 
for item in t: 
    print item.attrib["no"] 
    print item.text 

PS: 您可以ET.fromstring替代ET.parse,改變輸入參數字符串類型 它的工作原理