Monday, September 9, 2013

Python: Create an XML and append child node


from xml.etree.ElementTree import ElementTree
import xml.etree.cElementTree as ET
import os

def xmlFileCreate(keyword,status):
    root = ET.Element("Results")
    doc = ET.SubElement(root, "Result")
    field1 = ET.SubElement(doc, "keyword")
    field1.text = keyword
    field2 = ET.SubElement(doc, "status")
    field2.text = status
    tree = ET.ElementTree(root)
    tree.write("filename.xml")
def appendChildNode(keyword,status):
    tree = ET.parse("filename.xml")
    root = tree.getroot()
    doc = ET.SubElement(root,"Result")
    field1 = ET.SubElement(doc, "keyword")
    field1.text = keyword
    field2 = ET.SubElement(doc, "status")
    field2.text = status
    #tree = ET.ElementTree(root)
    tree.write("filename.xml")
if __name__ == '__main__':
    keyword = "data"
    status = "Pass"
    if os.path.exists("filename.xml"):
        appendChildNode(keyword,status)
    else:
        xmlFileCreate(keyword,status)

No comments:

Post a Comment

Add Your comments here...