从url解析以下xml时遇到问题。
我的url路径中的示例XML:
<?xml version="1.0" encoding="utf-8"?>
<Documents>
<class>
<mid name="yyyyyyyyyyyyy"></mid>
<person name="yyyyyyyyyy"></person>
<url name="yyyyyyyyy"></url>
</class>
<class>
<mid name="xxxxx"></mid>
<person name="xxxxxxxxxx"></person>
<url name="xxxxxxxxxxx"></url>
</class>
</Documents>
下面是我的python代码;
def staff_list(request):
url = http://path.to.url/
dom = minidom.parse(urlopen(url))
person = dom.getElementsByTagName('person')
for i in person:
print i.attributes['name'].value
在forloop中,我想打印属于同一父类的xml中的person和url标记值。
我尝试了下面的迭代方法,但得到"太多的值无法打开">错误
def staff_list(request):
url = http://path.to.url/
dom = minidom.parse(urlopen(url))
person = dom.getElementsByTagName('person')
mid = dom.getElementsByTagName('mid')
url = dom.getElementsByTagName('url')
for i,j,k in person,mid,url:
print i.attributes['name'].value,j.attributes['name'].value,k.attributes['name'].value
有什么建议吗?
您想使用zip()
来组合元素,我认为:
for i,j,k in zip(person, mid, url):
不过帮自己一个大忙,改用ElementTree API;API比XML DOM API更为Python化和易于使用。
如果您想坚持使用minidom
,您可以将循环更改为:
for cls in dom.getElementsByTagName('class'):
person = cls.getElementsByTagName('person')[0]
mid = cls.getElementsByTagName('mid')[0]
url = cls.getElementsByTagName('url')[0]
print person.attributes['name'].value
print mid.attributes['name'].value
print url.attributes['name'].value
正如@Martijn Pieters所说,看看ElementTree作为API的替代品。例如:
import xml.etree.ElementTree as ET
documents = ET.fromstring(xmlstr)
for cls in documents.iter('class'):
person = cls.find('person')
mid = cls.find('mid')
url = cls.find('url')
print person.get('name'), mid.get('name'), url.get('name')
我会使用xpath和lxml.html:最低限度的方法:
import lxml.html as lh
doc=lh.parse(test.xml)
In [70]: persons = doc.xpath('.//person/@name')
In [71]: urls=doc.xpath('.//person[@name]/following-sibling::url/@name')
In [72]: mids=doc.xpath('.//person[@name]/preceding-sibling::mid/@name')
In [73]: [[p,m,u]for p,m,u in zip(persons, mids, urls)]
Out[73]:
[['yyyyyyyyyy', 'yyyyyyyyyyyyy', 'yyyyyyyyy'],
['xxxxxxxxxx', 'xxxxx', 'xxxxxxxxxxx']]