我目前正在研究 IRC Bot,并希望从 XML 文件中检索配置,如下所示:
<server>
<host> HOST1 </host>
<port> 6667 </port>
<channel>
<name> CHANNAME1</name>
</channel>
<channel>
<name> CHANNAME2 </name>
</channel>
</server>
<server>
<host> HOST2 </host>
<port> 6667 </port>
<channel>
<name> CHANNAME3 </name>
</channel>
</server>
我的代码如下所示:
doc = minidom.parse(xml)
node = doc.documentElement
servers = doc.getElementsByTagName("server")
for server in servers:
channels = server.getElementsByTagName("channel")
host = server.getElementsByTagName("host")[0].childNodes[0].data
print host
for channel in channels:
NAME = channel.getElementsByTagName("name")[0].childNode[0].data
print NAME
输出是
HOST1
CHANNAME1
CHANNAME2
CHANNAME3
HOST2
CHANNAME1
CHANNAME2
CHANNAME3
但我需要的只是
HOST1
CHANNAME1
CHANNAME2
HOST2
CHANNAME3
有没有办法在我的节点服务器中获取标签名称为“通道”的所有元素,而不是整个 xml 文件?