Writing an XML response doc in python is pretty easy.
While working on one of the projects i wrote some
methods thats make it even easy to use:
import xml.dom.minidom
class MyXml:
def __init__(self):
self.doc = xml.dom.minidom.Document()
def add_root(self, node_str):
"""creates and returns root node"""
root = self.doc.createElementNS("http://mynamespace.com", node_str)
self.doc.appendChild(root)
return root
def add_node(self, node, node_str):
"""creates and returns a child node"""
ch_node = self.doc.createElementNS("http://mynamespace.com", node_str)
node.appendChild(ch_node)
return root
def add_txt_value(self, node, value):
"""creates a text node and appends to existing node"""
txt_node = self.doc.createTextNode(str(value))
node.appendChild(txt_node)
#==================================================
# example to create a xml response document you can simply add nodes and text
#as given below
#<?xml version="1.0" encoding="utf-8"?>
# <response>
# <success> Hey i got your msg</success>
# </response>
#==================================================
if __name__ == '__main__':
xmlObj = MyXml()
#to create root node
root = xmlObj.add_root("response")
#to add child node arg1 parent node, arg2 child node
node1 = xmlObj.add_node(root, "success")
#to add success string to success node
xmlObj.add_txt_value(node1, "Hey i got your msg")
While working on one of the projects i wrote some
methods thats make it even easy to use:
import xml.dom.minidom
class MyXml:
def __init__(self):
self.doc = xml.dom.minidom.Document()
def add_root(self, node_str):
"""creates and returns root node"""
root = self.doc.createElementNS("http://mynamespace.com", node_str)
self.doc.appendChild(root)
return root
def add_node(self, node, node_str):
"""creates and returns a child node"""
ch_node = self.doc.createElementNS("http://mynamespace.com", node_str)
node.appendChild(ch_node)
return root
def add_txt_value(self, node, value):
"""creates a text node and appends to existing node"""
txt_node = self.doc.createTextNode(str(value))
node.appendChild(txt_node)
#==================================================
# example to create a xml response document you can simply add nodes and text
#as given below
#<?xml version="1.0" encoding="utf-8"?>
# <response>
# <success> Hey i got your msg</success>
# </response>
#==================================================
if __name__ == '__main__':
xmlObj = MyXml()
#to create root node
root = xmlObj.add_root("response")
#to add child node arg1 parent node, arg2 child node
node1 = xmlObj.add_node(root, "success")
#to add success string to success node
xmlObj.add_txt_value(node1, "Hey i got your msg")
good .. really helpful
ReplyDelete