練習-擷取XML資料
XML
是一種以符號分隔的檔案只具備兩個維度:列與欄(列內的欄位)。
如果想要在不同的程式之間轉換資料結構,你就要設法將階層、序列、集合與吉他結構編碼成文字。
XML就是處理這種事情的主要標記格式。他使用標籤來界定資料,例如下面的menu.xml
<?xml version="1.0"?>
<menu>
<breakfast hours="7-11">
<item price="$6.00">breakfast burritos</item>
<item price="$4.00">pancakes</item>
</breakfast>
<lunch hours="11-3">
<item price="$5.00">hamburger</item>
</lunch>
<dinner hours="3-10">
<item price="$8.00">spaghetti</item>
</dinner>
</menu>
可以看到XML的主要特點有以下:
- 標籤的開頭是<字元。所以這個範例可以看出標籤有menu、breakfast、lunch、dinner與item。
- 空白字元會被忽略
- 通常<menu>等開始標籤後面有其他內容,接著配對一個結束的標籤,例如</menu>
- 在標籤裡面可以有其他的標籤,層數不限。在這個範例中item是breakfast、lunch、dinner的子標籤,又是menu的子標籤。
- 開始標籤中可能有選用的屬性。這個範例中price就是item的屬性。
- 標籤裡面可以放值。這個範例中,每一個item都有一個值,例如第二個item標籤中的值是pancakes。
- 如果名為thing的標籤中沒有值或子標籤,可以用一個標籤表示<thing/> 可以直接取代一組<thing></thing>。
- 可以隨意決定資料(屬性、值、子標籤)的位置,例如我們可以將最後一個item標籤改成<item price="$9.99" food="anywhere"/>。
<?xml version="1.0"?>
<menu>
<breakfast hours="7-11">
<item price="$6.00">breakfast burritos</item>
<item price="$4.00">pancakes</item>
</breakfast>
<lunch hours="11-3">
<item price="$5.00">hamburger</item>
</lunch>
<dinner hours="3-10">
<item price="$8.00">spaghetti</item>
<item price="$9.99" food="anywherer"/>
</dinner>
</menu>
import xml.etree.ElementTree as et
tree=et.ElementTree(file='menu.xml')
#et.ElementTree 是用來創建XML樹的物件,file='menu.xml'是指定要解析XML的檔案路徑
root=tree.getroot()
#tree=getroot() 是ElementTree物件的一個方法,用來取得XML樹的根元素
#根元素是XML樹的最上層元素,他包含了XML樹的所有其他元素
print(root.tag)
for child in root:
print('tag:',child.tag,'attributes:',child.attrib,'查看字串')
for grandchild in child:
print('\ttag:',grandchild.tag,
'attributes:',grandchild.attrib,
'標籤中的字串:',grandchild.text)
----------------------------終端機
menu
tag: breakfast attributes: {'hours': '7-11'} 查看字串
tag: item attributes: {'price': '$6.00'} 標籤中的字串: breakfast burritos
tag: item attributes: {'price': '$4.00'} 標籤中的字串: pancakes
tag: lunch attributes: {'hours': '11-3'} 查看字串
tag: item attributes: {'price': '$5.00'} 標籤中的字串: hamburger
tag: dinner attributes: {'hours': '3-10'} 查看字串
tag: item attributes: {'price': '$8.00'} 標籤中的字串: spaghetti
tag: item attributes: {'price': '$9.99', 'food': 'anywherer'} 標籤中的字串: None
標籤: 練習

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁