开发者

Is there something like LINQ to XML in python for appengine?

Is there something that I can use to query XML in python like I can do in LINQ2XML? And if it would run on appen开发者_Go百科gine too. Pseudocode:

 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"))


Yes. Example XML file:

<?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>

Example script:

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']))

prints:

Jim
home -> 000-000-0000
work -> 111-111-1111
Fred
home -> 222-222-2222
work -> 333-333-3333

It's part of Python 2.5, so it should work in App Engine. You can adapt the script to get the XML from a URL.


You can use the ElementTree XML API for that. Example:

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"]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜