有什么东西可以用来在python中查询XML,就像我在LINQ2XML中可以做到的那样?如果它也会在appengine上运行。 伪代码:
xml = fetch("http://foo/bar.xml")
for person : xml.elements("person"):
print(person.attribute("name"))
for number : person.elements("number")
print(" %s %d",(number.attribute("type"),number.attribute("value"))
答案 0 :(得分:4)
是。示例XML文件:
<?xml version="1.1" encoding="iso-8859-1"?>
<container>
<person name="Jim">
<number type="home" value="000-000-0000"/>
<number type="work" value="111-111-1111"/>
</person>
<person name="Fred">
<number type="home" value="222-222-2222"/>
<number type="work" value="333-333-3333"/>
</person>
</container>
示例脚本:
from xml.etree.ElementTree import ElementTree
f = open('/path/to/xml/file', 'r')
xml = ElementTree(file=f)
for person in xml.findall('person'):
print(person.attrib['name'])
for number in person.findall('number'):
print('%s -> %s' % (number.attrib['type'], number.attrib['value']))
打印:
Jim
home -> 000-000-0000
work -> 111-111-1111
Fred
home -> 222-222-2222
work -> 333-333-3333
它是Python 2.5的一部分,因此它应该在App Engine中运行。您可以调整脚本以从URL获取XML。
答案 1 :(得分:2)
您可以使用ElementTree XML API。例如:
import xml.etree.ElementTree as ET
xml = ET.parse("bar.xml")
for person in xml.findall("person"):
print person.attrib["name"]
for number in person.findall("number"):
print " %s %d" % (number.attrib["type"], int(number.attrib["value"]))