此功能如何在XML树工作中搜索节点?

问题描述 投票:0回答:1
我无法理解什么是查找功能在做什么

def lookup(d, key): found = False for child in d: if found : return child.text if child.tag == 'key' and child.text == key : found = True return None

这是完整的代码,同样,如果您需要查找library.xml文件,则可以转到此链接以查看更多上下文:
Https://www.py4e.com/code4.com/code3.zip

下载zip文件,然后可以转到曲目文件以查找库库文件。 import xml.etree.ElementTree as ET import sqlite3 conn = sqlite3.connect('trackdb.sqlite') cur = conn.cursor() # Make some fresh tables using executescript() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Track; CREATE TABLE Artist ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Album ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE ); CREATE TABLE Track ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER, len INTEGER, rating INTEGER, count INTEGER ); ''') fname = input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'Library.xml' # <key>Track ID</key><integer>369</integer> # <key>Name</key><string>Another One Bites The Dust</string> # <key>Artist</key><string>Queen</string> def lookup(d, key): found = False for child in d: if found : return child.text if child.tag == 'key' and child.text == key : found = True return None stuff = ET.parse(fname) all = stuff.findall('dict/dict/dict') print('Dict count:', len(all)) for entry in all: if ( lookup(entry, 'Track ID') is None ) : continue name = lookup(entry, 'Name') artist = lookup(entry, 'Artist') album = lookup(entry, 'Album') count = lookup(entry, 'Play Count') rating = lookup(entry, 'Rating') length = lookup(entry, 'Total Time') if name is None or artist is None or album is None : continue print(name, artist, album, count, rating, length) cur.execute('''INSERT OR IGNORE INTO Artist (name) VALUES ( ? )''', ( artist, ) ) cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, )) artist_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id) VALUES ( ?, ? )''', ( album, artist_id ) ) cur.execute('SELECT id FROM Album WHERE title = ? ', (album, )) album_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Track (title, album_id, len, rating, count) VALUES ( ?, ?, ?, ?, ? )''', ( name, album_id, length, rating, count ) ) conn.commit()

功能可以使用DOC字符串!如果您查看the的孩子XML元素,您会看到类似的条目
python xml
1个回答
0
投票
<dict>

SO,键/值对实际上是2个同级元素,一个接一个。第二个元素标签名称很难猜测,因为它编码类型(String / Integer / etc)。这使得很难搜索。但是您知道这是下一个元素,这就是循环的作用。当循环找到带有所需文本的元素时,它会设置
<key>Track ID</key><integer>369</integer> <key>Name</key><string>Another One Bites The Dust</string>

。循环的
next
圆形是带有您想要的值的元素。

如果循环找不到您想要的文本,它将退出,然后您返回

found = True

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.