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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming Languages-Other

From novice to tech pro — start learning today.