parse xml with python

i need to read in an xml file and find several attributes in it. For example i need to get the ip address and service name IIS Admin out of this xml:
   <ip address="" subnetmask="" />
  <service name="IIS Admin" startmode="Auto" started="True" startname="LocalSystem" />
Who is Participating?
ghostdog74Connect With a Mentor Commented:
you should use a XML parser, eg PyXML. However, if your request is just extract these 2 information, just simple string manipulation will do

for line in open("xmlfile"):
    if "</computer" in line: f=0
    if "<computer>" in line: f=1
    if f :
        if "<ip address" in line:
            print ip.replace('"',"")
        if "<service name" in line:
            service=line.split('" ')[0].split("=")[-1]
            print service.replace('"',"")

Open in new window

bman87Author Commented:
thanks for that solution. It didn't work straight up, but i modified the code so it does.


xmldoc = open('server.xml','r')
for line in xmldoc:
    line = line.lstrip()
    line = line.split('"')
    if "<ip address=" in line[0]:
        print line[1]
    if "<service name=" in line[0]:
        print line[1]

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.