Python XML Minidom Get element by tag in child node

I am currently working on IRC Bot and want to get the configuration from an XML file that looks like this:

<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> 

And my code looks like this:

 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 

And conclusion

 HOST1 CHANNAME1 CHANNAME2 CHANNAME3 HOST2 CHANNAME1 CHANNAME2 CHANNAME3 

But I only need

 HOST1 CHANNAME1 CHANNAME2 HOST2 CHANNAME3 

Is there a way to get all elements with the tag name "channel" in my node server instead of the whole XML file?

+6
source share
2 answers

Your code looks right as it is. You have childNode when it should be childNodes in the NAME assignment, but I assume this is just a typo in your question.

However, your XML is not valid. You must have some kind of root directory node wrapping the servers. As it is currently written, I would not expect to even make out successfully. It should look something like this:

 <servers> <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> </servers> 

With this XML and the code you provided, I get the exact result you expect.

+4
source

Do not use the mini disc. Use the ElementTree API instead. It can handle subtrees much better:

 from xml.etree import ElementTree as ET doc = ET.parse(xmlfile).getroot() for server in doc.findall('server'): host = server.find('./host').text print host for channel in server.findall('channel'): name = channel.find('name').text print name 
+3
source

Source: https://habr.com/ru/post/948420/


All Articles