?
Solved

Create XML from python script

Posted on 2009-04-05
12
Medium Priority
?
720 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
A new era in Cloud training has arrived.

A day that will go down in Cloud history.. But are you ready for it? Will you accept this Cloud challenge?

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

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

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

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses
Course of the Month11 days, 7 hours left to enroll

752 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