我有一个程序从套接字读取xml文档.我将xml文档存储在一个字符串中,我希望将其直接转换为Python字典,就像在Django的simplejson库中完成一样.
举个例子:
str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></person"
dic_xml = convert_to_dic(str)
Run Code Online (Sandbox Code Playgroud)
然后dic_xml看起来像{'person' : { 'name' : 'john', 'age' : 20 } }
假设我有一个XML文件,如下所示.
<A>
<B>
<C>"blah"</C>
<C>"blah"</C>
</B>
<B>
<C>"blah"</C>
<C>"blah"</C>
</B>
</A>
Run Code Online (Sandbox Code Playgroud)
我需要将此文件读入类似这样的字典中.
dict["A.B1.C1"] = "blah" dict["A.B1.C2"] = "blah" dict["A.B2.C1"] = "blah" dict["A.B2.C2"] = "blah"
但是dict的格式并不重要,我只想将所有信息都读入Python的变量中.
问题是我不知道XML的结构,我只想读取字典中的所有信息.
有没有办法用Python做到这一点?
我已经围绕这个问题做了一些研究,但还没有真正能够提出任何有用的东西.我需要的不仅是解析和阅读,而是实际操作python中的XML文档,类似于JavaScript能够操作HTML文档的方式.
请允许我举个例子.说我有以下XML文档:
<library>
<book id=123>
<title>Intro to XML</title>
<author>John Smith</author>
<year>1996</year>
</book>
<book id=456>
<title>XML 101</title>
<author>Bill Jones</author>
<year>2000</year>
</book>
<book id=789>
<title>This Book is Unrelated to XML</title>
<author>Justin Tyme</author>
<year>2006</year>
</book>
</library>
Run Code Online (Sandbox Code Playgroud)
我需要一种方法既能检索元素,无论是使用XPath或用"Python化"的方法,如概括在这里,但我也需要能够操纵的文档,如下面:
>>>xml.getElement('id=123').title="Intro to XML v2"
>>>xml.getElement('id=123').year="1998"
Run Code Online (Sandbox Code Playgroud)
如果有人知道Python中的这样一个工具,请告诉我.谢谢!
我正在使用谷歌网站检索天气信息,我想在XML标签之间找到值.下面的代码给我一个城市的天气状况,但我无法获得其他参数,如温度,如果可能的话,解释代码中隐含的分离函数的工作:
import urllib
def getWeather(city):
#create google weather api url
url = "http://www.google.com/ig/api?weather=" + urllib.quote(city)
try:
# open google weather api url
f = urllib.urlopen(url)
except:
# if there was an error opening the url, return
return "Error opening url"
# read contents to a string
s = f.read()
# extract weather condition data from xml string
weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0]
# if there was an error getting the condition, the city is invalid
if weather == "<?xml version=":
return …Run Code Online (Sandbox Code Playgroud)