解析xml文件并用检索到的数据提供对象列表

问题描述 投票:0回答:1

编辑:在帖子底部添加了一个可供查看的工作解决方案。

因此,每次我接触xml时,我都想撞墙。通常是为了编写文件,我最终设法找到解决所有不一致的方法,但是这次我必须解析文档。

这里是场景:我有一个xml文档,其中列出游戏和每个游戏的某些属性(或子节点?实际上我不确定)。我想要的是:

For each game:
 Gets it's path, name, and genre
 Build a Game object with this
 Store the object in an array list

我了解“ findall”命令,但不了解如何在它们之间链接数据。由于它是一棵树,我想我应该能够从一个游戏到另一个游戏,获取所需的数据,然后继续进行下一个游戏,但是我被困住了。

所以这是我需要解析的xml文件的摘录:

<?xml version="1.0"?>
<gameList>
    <provider>
        <System>Megadrive</System>
        <software>Skraper</software>
        <database>ScreenScraper.fr</database>
        <web>http://www.screenscraper.fr</web>
    </provider>
    <game id="574" source="ScreenScraper.fr">
        <path>./3 Ninjas Kick Back.zip</path>
        <name>3 Ninjas Kick Back</name>
        <genre>Platform-Action</genre>
    </game>
    <game id="394" source="ScreenScraper.fr">
        <path>./688 Attack Sub.zip</path>
        <name>688 Attack Sub</name>
        <genre>Simulation</genre>
    </game>
</gameList>

这是我当前的代码,在沙箱中,正在尝试并遇到状态:

import os
from xml.etree import ElementTree


class GameListParser:
    GAMELIST_FILE = 'gamelist.xml'

    GAMELIST_KEY = "gameList"
    GAME_KEY = "game"
    GENRE_KEY = "genre"
    PATH_KEY = "path"
    NAME_KEY = "name"

    keys_map = {
        GAMELIST_KEY: {
            GAME_KEY: [NAME_KEY, GENRE_KEY, PATH_KEY]
        }
    }

    def __init__(self, gamelist_path):
        self.gamelist = os.path.join(gamelist_path, self.GAMELIST_FILE)
        self.parsed_gamelist = None
        self.__parse()

    def __parse(self):
        self.parsed_gamelist = ElementTree.parse(self.gamelist)

    def __get_root(self):
        return self.parsed_gamelist.getroot()

    def get_all_games(self):
        return self.parsed_gamelist.findall(self.GAME_KEY)

    def print_games_details(self):
        for node in self.get_all_games():
            for game in node.getiterator():
                name = game.attrib.get(self.NAME_KEY)
                genre = game.attrib.get(self.GENRE_KEY)

[我只希望使用print_games_details方法来打印游戏数据,但实际上节点和游戏对象是相同的,因此名称和类型均为None,我不检索所需的数据。

我很确定这很简单,但是我一生中只能使用xml 3-4次,而我唯一必须解析为对象的是C ++,它是系统的完整重构。另外两次是在Matlab和Python中,将方向对象指向xml文件。每次遇到麻烦时,我都无法理解树的逻辑,如何解析/创建树,并且在线资源对我没有太大帮助。

编辑:所以我研究了一个解决方案,尽管它给了我结果,但我希望我对此完全不满意。我的问题是这种解决方案意味着我只需要遍历xml文件的结构就可以了。

我无法用它来做一些通用的事情,这是我使用xml方法时主要关注的问题之一。

如果你们中的任何一个都可以请以下代码并提供反馈和改进,我将不胜感激:

import os
from xml.etree import ElementTree


class GameListParser:
    GAMELIST_FILE = 'gamelist.xml'

    GAME_ID = 'id'
    GAME_KEY = "game"
    GENRE_KEY = "genre"
    PATH_KEY = "path"
    NAME_KEY = "name"

    keys_map = [NAME_KEY, GENRE_KEY, PATH_KEY]
    game_map = {}

    def __init__(self, gamelist_path):
        self.gamelist = os.path.join(gamelist_path, self.GAMELIST_FILE)
        self.parsed_gamelist = None
        self.__parse()

    def __str__(self):
        text_output = []

        for game_id, game in self.game_map.items():
            text_output.append("Game " + game_id + " has properties:")
            for key, value in game.items():
                text_output.append(key + ": " + value)
            text_output.append("\n")

        return "\n".join(text_output)

    def __get_game_id(self, game):
        return game.get(self.GAME_ID)

    def __game_is_valid(self, game):
        return self.__get_game_id(game) is not None

    def __get_all_games(self):
        return self.parsed_gamelist.findall(self.GAME_KEY)

    def __process_all_games(self):
        for game in self.__get_all_games():
            self.__process_game_nodes(game)

    def __process_game_nodes(self, game):

        if self.__game_is_valid(game):

            details = {}
            self.game_map[self.__get_game_id(game)] = details

            for key in self.keys_map:
                game_child = game.find(key)
                if game_child is not None:
                    details[key] = game_child.text
                else:
                    details[key] = ""

    def __parse(self):
        self.parsed_gamelist = ElementTree.parse(self.gamelist)
        self.__process_all_games()
python xml xml-parsing
1个回答
1
投票

[推荐第三方库:SimplifiedDoc。点安装-U简化_scrapy

from simplified_scrapy import SimplifiedDoc
html = '''
<?xml version="1.0"?>
<gameList>
    <provider>
        <System>Megadrive</System>
        <software>Skraper</software>
        <database>ScreenScraper.fr</database>
        <web>http://www.screenscraper.fr</web>
    </provider>
    <game id="574" source="ScreenScraper.fr">
        <path>./3 Ninjas Kick Back.zip</path>
        <name>3 Ninjas Kick Back</name>
        <genre>Platform-Action</genre>
    </game>
    <game id="394" source="ScreenScraper.fr">
        <path>./688 Attack Sub.zip</path>
        <name>688 Attack Sub</name>
        <genre>Simulation</genre>
    </game>
</gameList>
'''
doc = SimplifiedDoc(html)
games = doc.gameList.games
datas = [[g.path.text,g.name.text,g.genre.text] for g in games]
print (datas)

结果:

[['./3 Ninjas Kick Back.zip', '3 Ninjas Kick Back', 'Platform-Action'], ['./688 Attack Sub.zip', '688 Attack Sub', 'Simulation']]

这里有更多示例:https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

© www.soinside.com 2019 - 2024. All rights reserved.