首页 > 解决方案 > 如何使用 Python 读取 xml 文件中的嵌套节点?

问题描述

我正在编写一个文本冒险游戏,我想将玩家可以在每个位置拾取的位置和项目存储在 XML 文件中。游戏应该读取 XML 文件并创建包含项目对象以及该位置的其他属性的位置对象。

我已经通过修改代码以满足我的需要尝试了以下两个教程: https ://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree https://www。 tutorialspoint.com/python/python_xml_processing.htm

下面是 XML 文件:

<locations>
<location id="0">
    <descr>"You are in a hallway in the front part of the house. There is the front door to the north and rooms to the east and to the west. The hallway stretches back to the south."</descr>
    <exits>"N,W,S,E""</exits>
    <neighbors>"1,2,3,4"</neighbors>
    <item itemId="2">
        <name>"rusty key"</name>
        <description>this key looks old</description>
        <movable>true</movable>
        <edible>false</edible>
    </item> 
    <item itemId="1">
        <name>"hat"</name>
        <description>An old hat</description>
        <movable>true</movable>
        <edible>false</edible>
    </item>
</location>
<location itemId="1">
    <descr>"You are in the front yard of a brick house. The house is south of you and there is a road leading west and east."</descr>
    <exits>"S"</exits>
    <neighbors>"0"</neighbors>
    <item itemId="3">
        <name>"newspaper"</name>
        <description>today's newspaper</description>
        <movable>true</movable>
        <edible>false</edible>
    </item>    
</location>

现在我只是想打印出各种属性。一旦我知道如何访问它们,将它们放入构造函数以创建对象将是容易的部分。这是我到目前为止的代码。我可以轻松访问位置节点的所有属性,但我只能访问每个项目的 ID。我不知道如何访问其他属性,例如名称、描述等。

import xml.etree.ElementTree as ET
tree = ET.parse('gamefile.xml')
root = tree.getroot()


for x in range(0,len(root)):
   print("description: "+root[x][0].text)
   print("exits: "+root[x][1].text)
   print("neighbors: "+root[x][2].text)
   for child in root[x]:
      if child.tag =='item':
         print(child.attrib)

标签: pythonxmlparsingelementtree

解决方案


您用于解析 XML 的代码依赖于标签顺序。试着这样写:

from xml.etree import ElementTree as ET

tree = ET.parse('gamefile.xml')
locations = tree.getroot()

for location in locations:
    desc = location.findall('descr')
    exits = location.findall('exits')
    neighbors = location.findall('neighbors')
    print(desc[0].text)
    print(exits[0].text)
    print(neighbors[0].text)
    for item in location.findall('item'):
        for attr in item:
            print('{0}: {1}'.format(attr.tag, attr.text))

更好的方法是在 XML 和 python 对象之间进行序列化/反序列化。


推荐阅读