python 生成xml

用到这个模块的时候,感觉网上大部分资料比较繁琐,所以自己写了个简单的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)

转载于:https://my.oschina.net/u/3360163/blog/1594178

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值