如何在python中发布xml元素 [英] How to POST an xml element in python

查看:68
本文介绍了如何在python中发布xml元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有这个xml元素(xml.etree.ElementTree),我想将其发布到url.目前我正在做类似的事情

Basically I have this xml element (xml.etree.ElementTree) and I want to POST it to a url. Currently I'm doing something like

xml_string = xml.etree.ElementTree.tostring(my_element)
data = urllib.urlencode({'xml': xml_string})
response = urllib2.urlopen(url, data)

我很确定这一切都可行,但是我想知道是否有一些更好的实践或方法,而无需先将其转换为字符串.

I'm pretty sure that works and all, but was wondering if there is some better practice or way to do it without converting it to a string first.

谢谢!

推荐答案

如果这是您自己的API,我会将POST视为application/xml.默认值为application/x-www-form-urlencoded,用于HTML表单数据,而不是单个XML文档.

If this is your own API, I would consider POSTing as application/xml. The default is application/x-www-form-urlencoded, which is meant for HTML form data, not a single XML document.

req = urllib2.Request(url=url, 
                      data=xml_string, 
                      headers={'Content-Type': 'application/xml'})
urllib2.urlopen(req)

这篇关于如何在python中发布xml元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆