Read and Update with httplib as XML

From Devipedia

Jump to: navigation, search
import httplib, libxml2

conn = httplib.HTTPConnection("www.nexgendatatest.net")

conn.request("GET", "/universe/visionael/vendorset/xml/?1=1174")
r1 = conn.getresponse()
print r1.status
200
print r1.reason
OK
data1 = r1.read()
print data1
<?xml version="1.0" encoding="ASCII"?>
<nexgen>
  <data>
    <item key="properties">
      <item key="city">Sunnyvale</item>
      <item key="address1">NokiaTelecommunications Inc.</item>
      <item key="address2">232 E. Java Drive</item>
      <item key="comments">None</item>
      <item key="state">CA</item>
      <item key="country">united states</item>
      <item key="vendor_name">Ipsilon Networks Inc.</item>
      <item key="id">1174</item>
      <item key="account_no">None</item>
    </item>
    <item key="title">VISIONAEL VENDORSET</item>
    <item key="xml_uri">http://www.nexgendatatest.net/universe/visionael/vendorset/xml/xml/?1=1174</item>
    <item key="uri">http://www.nexgendatatest.net/universe/visionael/vendorset/xml/?1=1174</item>
    <item key="all_uri">http://www.nexgendatatest.net/universe/visionael/vendorset/xml/?1=1174&__ngd__allattrs=true</item>
    <item key="rootsite">http://www.nexgendatatest.net/</item>
    <item key="json_uri">http://www.nexgendatatest.net/universe/visionael/vendorset/xml/json/?1=1174</item>
  </data>
</nexgen>

doc = libxml2.parseDoc(data1)
ctxt = doc.xpathNewContext()

# find and view properties

res = ctxt.xpathEval('//item[@key="properties"]')
for r in res:
   print r

<item key="properties">
      <item key="city">Sunnyvale</item>
      <item key="address1">NokiaTelecommunications Inc.</item>
      <item key="address2">232 E. Java Drive</item>
      <item key="comments">None</item>
      <item key="state">CA</item>
      <item key="country">united states</item>
      <item key="vendor_name">Ipsilon Networks Inc.</item>
      <item key="id">1174</item>
      <item key="account_no">None</item>
</item>

# find city name
res = ctxt.xpathEval('//item[@key="city"]')[0]
print res.content
Sunnyvale
Personal tools