Solved

Create XML from python script

Posted on 2009-04-05
12
702 Views
Last Modified: 2012-05-06
I need to generate an xml file of this form from a python script:

<?xml version="1.0" encoding="UTF-8"?>
<hosts>
	<host>
		<name>Computer1</name>
		<ip>127.0.0.1</ip>
		<scan>03/04/2009</scan>
		<config>test.conf</config>
		<enabled>yes</enabled>
	</host>
	<host>
		<name>Computer2</name>
		<ip>127.0.0.1</ip>
		<scan>03/04/2009</scan>
		<config>test.conf</config>
		<enabled>yes</enabled>
	</host>
</hosts>

Open in new window

0
Comment
Question by:bman87
  • 6
  • 6
12 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24073772
For a simple structure like this, you can just write it as a text file. In what form do you have the data? In a database, in a list of dictionaries, list of tuples, list of objects or something else?
0
 

Author Comment

by:bman87
ID: 24073819
actually what i am planning on doing is scanning a directory which has this structure:

Computers (top level folder)
  |---Computer1 (folder)
     |----Dir1 (folder)
     |----Dir2 (folder)
     |----settings.conf (config file)
  |---Computer2 (folder)
      |----Dir1 (folder)
      |----Dir2 (folder)
      |----settings.conf (config file)

Where there is a seperate folder for each computer. Inside each folder, there is a settings file which is of the format:

name = computer1
ip = 127.0.0.1
....

i basically want to go to each one of these files, and append it to the xml file.

0
 

Author Comment

by:bman87
ID: 24073826
i forgot to mention that there are many settings in this settings.conf file, and i only want the ones specified in the xml file
0
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24073933
To fetch the files, use glob:

import glob
files = glob.glob('Computers/*/settings.conf')

Loop over the files like this:

for filename in files:
    data = file(filename,'r').read()
    settings = GetSettings(data)
    print MakeXml(settings)

GetSettings() makes a dictionary from the content of the file, makeXml() creates the XML "record". I don't know if these settings files have comments, I inserted a mechanism to allow for standard # line comments, see below. Instead of printing it, you can write it to a file:

xml = open('Settings.xml','w');
xml.write('<?xml version="1.0" encoding="UTF-8"?>\n')
xml.write('<hosts>\n');
for filename in files:
    data = file(filename,'r').read()
    settings = GetSettings(data)
    xml.write(MakeXml(settings))
xml.write('</hosts>');
xml.close()
def GetSettings(data):
    lines = data.split('\n')
    res = {}
    for line in lines:
        if line and (line[0]=='#'):
          continue
        tmp = line.split('=')
        if(len(tmp)==2):
            res[tmp[0]] = tmp[1]
    return res
 
def MakeXml(settings):
    return """    <host>
        <name>%(name)s</name>
        <ip>%(ip)s</ip>
        <scan>%(scan)s</scan>
        <config>%(config)s</config>
        <enabled>%(enabled)s</enabled>
    </host>\n""" % settings

Open in new window

0
 

Author Comment

by:bman87
ID: 24073987
the settings file looks like the one attached. in the statement:

for filename in files:
    data = file(filename,'r').read()
    settings = GetSettings(data)
    print MakeXml(settings)

what does filename refer to? is this the attirbute, ie name or ip or is the value?

settings.txt
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24074028
It is the file name including a relative path, fetched using glob.glob(). Run this code to see if you get the correct files:

import glob
files = glob.glob('Computers/*/settings.conf')
print files

You may need to adjust the path, depending on what is the current working directory when you run the script.
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24074034
You may need to modify line 9 from my snippet above. Change this:

res[tmp[0]] = tmp[1]

...into this:

res[tmp[0].strip()] = tmp[1].strip()

This will remove unwanted spaces.
0
 

Author Comment

by:bman87
ID: 24074112
i ran
import glob
files = glob.glob('Computers/*/settings.conf')
print files

and it printed all the fiels correctly, with a list like ['computer1\\settings.conf', 'computer2\\settings.conf', 'computer3\\settings.conf'].
This is where i dont understand that for loop. What do i substitue for filename? Do i have to put a specific name - 'computer1\\settings.conf', because that gives a syntax error. Or do i put something like '*/settings.conf'.
Sorry but i am failry new to python, still learning.

I also got an error, i will attach the code i ran and the error.

import glob
files = glob.glob('*/settings.conf')
 
def GetSettings(data):
    lines = data.split('\n')
    res = ()
    for line in lines:
        if line and (line[0]=='#'):
            continue
        tmp = line.split('=')
        if  (len(temp)==2):
            res[tmp[0].strip()] = tmp[1].strip()
    return res
 
def MakeXML(settings):
    return """  <host>
        <name>%(name)s</name>
        <ip>%(ip)s</ip>
        <scan>%(scan)s</scan>
        <config>%(config)s</config>
    </host>\n""" %settings
 
for computer1 in files:
    data = file(computer1, 'r').read()
    settings = GetSettings(data)
    print MakeXML(settings)
 
xml = open('settings.xml', 'w')
xml.write('<?xml version="1.0" encoding="UTF-8"?>\n')
xml.write('<hosts>\n')
for computer1 in files:
    data = file(computer1, 'r').read()
    settings = GetSettings(data)
    xml.write(MakeXML(settings))
xml.write('</hosts>')
xml.close(

Open in new window

error.txt
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24074137
Line 11 should be:

        if  (len(tmp)==2):

"tmp", not "temp".

In python, when you have a list L, and iterate over it with a for loop like this:

for item in L:
    print item

... the "item" variable is assigned each item in the list L, changing the value of "item" as it iterates trough the list.

The "filename" variable will contain the filename from the "files" list. In your code, you have called this "computer1", it is still just a variable name, and it will contain the names for each of the files, not just for computer1.

You can remove lines 23-26, this was just example code, outputting the XML to the screen. Lines 28-36 writes to the file.
0
 

Author Comment

by:bman87
ID: 24074181
it is creating an xml file, but it is empty. I get the error:
in line 12,  in GetSettings
res[tmp[0].strip()] = tmp[1].strip
TypeError: 'tuple' object does not support item assignment

0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
ID: 24074186
Line 6 in your snippet above is wrong:

    res = ()

change it to:

    res = {}

This makes it a dictionary.
0
 

Author Comment

by:bman87
ID: 24074194
Thats great, works like a charm. Cheers.
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question