hello all i want ask something about xml and python
example i have 1 file with extention .txt and in that file i have 4 statement

ndoe
bali
swimming
male

and i want convert that file to xml like this

<name> ndoe </name>
<home> bali </home>
<hoby> swimming </hoby>
<gender> male </male>

how to convert like that?
any library can i use? or i must to convert 1 by 1 every statement in 1 file
thanks for your answer

Every XML document must have a declaration and a root element. I may do something like this:

data = """ndoe
bali
swimming
male"""

tag_list = ['name', 'home', 'hobby', 'gender']

xml_data_list = ['<?xml version="1.0" encoding="ISO-8859-1"?>','<people>']

for i, item in enumerate(data.split()):
    xml_data_list.append("<%s>%s</%s>" % (tag_list[i], item, tag_list[i]))

xml_data_list.append('</people>')

print '\n'.join(xml_data_list)

Output:
>>> <?xml version="1.0" encoding="ISO-8859-1"?>
<people>
<name>ndoe</name>
<home>bali</home>
<hobby>swimming</hobby>
<gender>male</gender>
</people>
>>>

The problem here is that you're adding information to the file: you must give your program a way to know that "ndoe" is a "name", "swimming" a "hobby", etc. This depends essentially on your file: you may have a succession of records with the same sequence name-home-hobby-gender repeated in this order, or you could teach your program that "male" or "female" is a "gender" for example.

Without this information about the structure of your file, I don't think the problem can be seriously solved. I give you a very basic function which could help

def surround(tag_name, data):
  return "<%(tag)s>%(data)s</%(tag)s>" % {'tag': tag_name, 'data': data}

print surround("hobby", "swimming") # prints "<hobby>swimming</hobby>"

OK i will try this,but how if a data in file with extension txt and i want to convert to file with extension xml
thanks

thanks for answer
i have a new question how to make the xml have attribut node e.g
data.txt

ndoe
bali
swimming
male

data.xml
<person>
<object name = "first" > ndoe </object>
<object home = "now"> bali </object>
<object hobby = "most"> swimming </object>
<object gender = "now"> male </object>
</person>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.