python 生成xml

来源:互联网 发布:h2o 数据挖掘 编辑:程序博客网 时间:2024/06/05 16:44

用到这个模块的时候,感觉网上大部分资料比较繁琐,所以自己写了个简单的def


其实最主要掌握以下几个函数
1.doc=xml.dom.minidom.Document()#生成xml的dom树对象
2.root=doc.createElement("root")#创建树节点,可以使根节点或者是子节点
3.child.setAttribute('value',value)#设置节点属性
4.root.appendChild(child)#确定子节点与根节点依赖关系
5.child.appendChild(doc.createTextNode('hello world'))#向节点中插入文本内容

示例如下:

def writexml(servername,ip,port,provider,description,value):    try:        fp=open("C:\\Users\xxx\Desktop\Python3.6.2\域名解析\xxx.xml","w",encoding="utf-8")        try:            doc=xml.dom.minidom.Document()            root=doc.createElement("root")            doc.appendChild(root)            child1=doc.createElement("server")            child1.setAttribute('name',servername)            child_error=doc.createElement("error")            child_error.setAttribute('description', description)            child_error.setAttribute('value',value)            child2=doc.createElement("address")            child3=doc.createElement('addr')            child3.setAttribute('ip',ip[0])            child3.setAttribute('port', port[0])            child3.setAttribute('provider', provider[0])            child4=doc.createElement('addr')            child4.setAttribute('ip', ip[1])            child4.setAttribute('port', port[1])            child4.setAttribute('provider', provider[1])            #child3.appendChild(doc.createTextNode('hello world'))            child5 = doc.createElement('addr')            child5.setAttribute('ip', ip[2])            child5.setAttribute('port', port[2])            child5.setAttribute('provider', provider[2])            root.appendChild(child_error)            child2.appendChild(child3)            child2.appendChild(child4)            child2.appendChild(child5)            root.appendChild(child1)            root.appendChild(child2)            doc.writexml(fp,indent='\t', addindent='\t', newl='\n', encoding="UTF-8")        except :            traceback.print_exc()            logging.warning("writexml allerror%s"%traceback.print_exc())        finally:            fp.close()    except OSError as err:        print("OS error: {0}".format(err))        logging.warning('writexml OSError:%s'%err)    except ValueError:        print("Could not convert data to an integer.")        logging.warning('writexml ValueError:%s'%ValueError)

原创粉丝点击