第一个问题。如果我搞砸了告诉我。在
好的,我需要做的是以下几点。我尝试使用Python从API获取一些数据。API以XML格式发送给我。我试图用ElementTree来解析它。在
现在每次我从API请求信息时,都是不同的。我想把我得到的所有数据都列出来。我可以使用Python的列表,但是既然我想在最后将它保存到一个文件中,我想为什么不也使用ElementTree呢。在
从一个元素开始,我们称之为ListE。调用API,解析XML,从ElementTree获取根元素。将根元素作为子元素添加到ListE中。再次调用API,然后从头开始。在结尾ListE应该是一个元素,其子元素是每个API调用的结果。最后,为了使用ElementTree write()函数,一切都结束了。下面是代码。在
import xml.etree.ElementTree as ET
url = "http://http://api.intrade.com/jsp/XML/MarketData/ContractBookXML.jsp?id=769355"
try:
returnurl=urlopen(url)
except IOError:
exit()
tree = ET.parse(returnurl)
root = tree.getroot()
print "root tag and attrib: ",root.tag, root.attrib
historyE = ET.Element('historical data')
historyE.append(root)
historyE.append(root)
historyET = ET.ElementTree(historyE)
historyET.write('output.xml',"UTF-8")
程序不会返回任何错误。问题是当我要求浏览器打开它时,它声称有语法错误。用记事本打开文件我发现:
^{pr2}$我认为语法错误的原因是'historical data'和'ContractBookInfo lastUpdateTime=“0”'之间没有空格或返回。建议?在
问题在于:
你不应该用空格。总结于Wikipedia:
有关详细信息,请参见XML规范的this section(“名称中几乎允许使用所有字符,除了那些作为分隔符或可以合理使用的字符。”)
相关问题 更多 >
编程相关推荐