【发布时间】:2018-12-25 03:17:42
【问题描述】:
我正在编写一个文本冒险游戏,我想将玩家可以在每个位置拾取的位置和物品存储在一个 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)
【问题讨论】:
标签: python xml parsing elementtree