如何使用 ElementTree 访问 iTunes xml 中的值元素?

我正在尝试从 xml 播放列表“导出”到 html 表以进行共享。但是 iTunes 库文件使用键值对而不是更有意义的 XML 标签。是否有一种简单的方法也可以获取<value>这些键/值对?


这让我得到了 的值<key>,即 Track ID Name Artist Album Artist 等,但我似乎无法找到一种方法来获取下一个键的值,即<integer>49924 或<string>Ep。35 | 你做什么......我可以(应该)用 ElementTree 来做这件事还是我应该继续使用正则表达式或其他一些库?谢谢!


data = '''<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">

<plist version="1.0">

<dict>

    <key>Major Version</key><integer>1</integer>

    <key>Minor Version</key><integer>1</integer>

    <key>Date</key><date>2019-01-21T07:31:15Z</date>

    <key>Application Version</key><string>12.8.0.150</string>

    <key>Features</key><integer>5</integer>

    <key>Show Content Ratings</key><true/>

    <key>Music Folder</key><string>file:///Users/Music/iTunes/iTunes%20Media/</string>

    <key>Library Persistent ID</key><string>75E62CF156F5AE1B</string>

    <key>Tracks</key>

    <dict>

        <key>49924</key>

        <dict>

            <key>Track ID</key><integer>49924</integer>

            <key>Name</key><string>Ep. 35 | What Do Your Morals Taste Like? | Guest: Jonathan Haidt</string>

            <key>Artist</key><string>Blaze Podcast Network</string>

            <key>Album Artist</key><string>Blaze Podcast Network</string>

            <key>Album</key><string>Something's Off with Andrew Heaton</string>

            <key>Genre</key><string>News &#38; Politics</string>

            <key>Kind</key><string>MPEG audio file</string>

            <key>Size</key><integer>48123940</integer>

            <key>Total Time</key><integer>3004133</integer>

            <key>Year</key><integer>2019</integer>

            <key>Date Modified</key><date>2019-01-13T01:10:30Z</date>

            <key>Date Added</key><date>2019-01-13T01:10:30Z</date>

            <key>Bit Rate</key><integer>128</integer>


人到中年有点甜
浏览 148回答 1
1回答

MMTTMM

问题:如何访问 iTunes xml 中的值元素以下解决方案使用lxml.etree.iterparse附加<key>带有以下<value>标签的标签来构建 Python&nbsp;dict {key:value}.使用的模块和内置函数:lxml.etree.iterparseobject.__iter__(self)收益声明from lxml import etreeimport ioclass Playlist:&nbsp; &nbsp; def __init__(self, fh):&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; Initialize 'iterparse' to generate 'start' and 'end' events on all tags&nbsp; &nbsp; &nbsp; &nbsp; :param fh: File Handle from the XML File to parse&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; self.context = etree.iterparse(fh, events=("start", "end",))&nbsp; &nbsp; def _parse(self):&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; Yield only at 'end' event, except 'start' from tag 'dict'&nbsp; &nbsp; &nbsp; &nbsp; :return: yield current Element&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; for event, elem in self.context:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if elem.tag == 'plist' or \&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (event == 'start' and not elem.tag == 'dict'):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield elem&nbsp; &nbsp; def _parse_key_value(self, key=None):&nbsp; &nbsp; &nbsp; &nbsp; _dict = {}&nbsp; &nbsp; &nbsp; &nbsp; for elem in self._parse():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if elem.tag == 'key':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = elem.text&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if elem.tag in ['integer', 'string', 'date']:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not key is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _dict[key] = elem.text&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = None&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Missing key for value {}'.format(elem.text))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elif elem.tag in ['true', 'false']:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _dict[key] = elem.tag == 'true'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elif elem.tag == 'dict':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not key is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _dict[key] = self._parse_dict(key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = None&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return elem, _dict&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Unknow tag {}'.format(elem.tag))&nbsp; &nbsp; def _parse_dict(self, key=None):&nbsp; &nbsp; &nbsp; &nbsp; elem = next(self._parse())&nbsp; &nbsp; &nbsp; &nbsp; elem, _dict = self._parse_key_value(elem.text)&nbsp; &nbsp; &nbsp; &nbsp; return _dict&nbsp; &nbsp; def __iter__(self):&nbsp; &nbsp; &nbsp; &nbsp; for elem in self._parse():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if elem.tag == 'dict':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield self._parse_dict()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Unknow tag {}'.format(elem.tag))if __name__ == "__main__":&nbsp; &nbsp; data = b'''<?xml...'''&nbsp; &nbsp; with io.BytesIO(data) as in_xml:&nbsp; &nbsp; &nbsp; &nbsp; for record in Playlist(in_xml):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("record:{}".format(record))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for key, value in record.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("{}:{}".format(key, value))输出:record:{'Major Version': '1', 'Minor Version': '1'... (omitted for brevity)&nbsp; &nbsp; Major Version:1&nbsp; &nbsp; Minor Version:1&nbsp; &nbsp; Date:2019-01-24T10:31:15Z&nbsp; &nbsp; Tracks:{'99244': {'Track ID': '99244', 'Artist': 'Blaze Podcast Network', ... (omitted for brevity)}}用 Python 测试:3.5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python