Question : Read a text file and write an XML out of it  :D

Hi, I just began Python (20 minutes ago) and I've read two tutorials and now I would need a headstart with what I need to do so I can then modify it with what I've leart so far.

So What I want to do is read a text file with approximatively this:
...
(gibberish)
(more gibberish)
...
MODULES
    {
        MD      0x002E      IMG      0      243      47      14      18      "Car1"
        MD      0x002F      IMG      0      223      57      16      18      "Car2"
...
    }
(gibberish)

and write an XML file starting from the word 'MODULES', so it would look like this:

   
      243
      47
   

   
      223
      57
   

...


I heard there are already scripts existing on the internet but I can't find them

Thanks!

Georges

Answer : Read a text file and write an XML out of it  :D

Try this...
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
import os, sys
import xml.dom.minidom
 
f=file(sys.argv[1])
result = file(sys.argv[2],"w")
 
doc = xml.dom.minidom.Document()
root=doc.createElementNS("", "someURIs")
doc.appendChild(doc.createProcessingInstruction("xml-stylesheet",
	"type=\"text/xsl\" href=\"multiple_input3.xsl\""))
doc.appendChild(root)
 
# read lines from in file
for line in f.readlines():
	node = doc.createElementNS("", "file")
	node.appendChild(doc.createTextNode(line))
	root.appendChild(node)
	
# write result
result.write(doc.toprettyxml(indent="  ",encoding="ISO-8859-1"))
Open in New Window Select All
Random Solutions  
 
programming4us programming4us