Mahaveer Bubanale
Mahaveer Bubanale

Reputation: 21

How to create xml dynamically?

 import xml.etree.ElementTree as ET

 var3 = raw_input("Enter the root Element: \n")
 root = ET.Element(var3) 
 var4 = raw_input("Enter the sub root Element: \n")
 doc = ET.SubElement(root, var4)   

 no_of_rows=input("Enter the number of Element for XML files: -    \n")

 def printme():

    var = raw_input("Enter Element: - \n")
    var1 = raw_input("Enter Data: - \n")

    ET.SubElement(doc, var).text =var1

    return;

    for num in range(0, no_of_rows):
        printme()

    tree = ET.ElementTree(root)
    file = raw_input("Enter File Name: - \n")
    tree.write(file)

    ET.ElementTree(root).write(file, encoding="utf-8", xml_declaration=True)         
    print "Xml file Created..!!"

I want to create xml dynamically using python.

How to create multiple sub roots?


I am giving file name from the console to store written elements in xml. It is giving this error:

TypeError: descriptor 'write' requires a 'file' object but received a 'str'

What should I do?

Upvotes: 1

Views: 2222

Answers (2)

nick_gabpe
nick_gabpe

Reputation: 5765

If you want create xml you may just do this:

from lxml import etree
try:
   root_text = raw_input("Enter the root Element: \n")
   root = etree.Element(root_text)
   child_tag = raw_input("Enter the child tag Element: \n")
   child_text = raw_input("Enter the child text Element: \n")
   child = etree.Element(child_text )
   child.text =child_text 
   root.append(child)
   with open('file.xml', 'w') as f:
      f.write(etree.tostring(root))
      f.close()
except ValueError:
    print("Occured Error")

Or if you want dynamic length you just use for loop.

Upvotes: -1

gugaheri
gugaheri

Reputation: 21

You are taking no. of elements from user but you are not using it. Use a loop and get element details from user within the loop as shown below:

import xml.etree.ElementTree as ET
try:
    no_of_rows=int(input("Enter the number of Element for XML files: -    \n"))
    root = input("Enter the root Element: \n")
    root_element = ET.Element(root)
    for _ in range(1, no_of_rows):
        tag = input("Enter Element: - \n")
        value = input("Enter Data: - \n")    
        ET.SubElement(root_element, tag).text = value

    tree = ET.ElementTree(root_element)
    tree.write("filename.xml")

    print("Xml file Created..!!")
except ValueError:
    print("Value Error")
except:
    print("Exception Occuured")
    enter code here

I hope this is what you want to achieve.

Upvotes: 2

Related Questions