簡體   English   中英

如何使用Python解析XML文件?

[英]How to parse an XML file using Python?

我試圖在xml文件中打印所有元素和屬性。 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>

我該怎么做? 另外,如何搜索拓撲內部的開關等元素?

這是我的工作代碼:

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.parse替換為ET.fromstring並將輸入參數更改為字符串類型

就像S.Lott所表達的那樣,你有太多的方法去撫摸這只貓,

這是一個使用 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')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM