如何使用Python读取xml文件中的嵌套节点?

时间:2018-12-25 03:17:42

标签: python xml parsing elementtree

我正在编写一个文字冒险游戏,我想将玩家可以在每个位置提取的位置和物品存储在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)

1 个答案:

答案 0 :(得分:0)

您用于解析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对象之间进行序列化/反序列化。