XML mit etree Python analysieren
-
21-12-2019 - |
Frage
für dieses XML
<locations>
<location>
<locationid>1</locationid>
<homeID>281</homeID>
<buildingType>Added</buildingType>
<address>A</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
<location>
<locationid>2</locationid>
<homeID>81</homeID>
<buildingType>Added</buildingType>
<address>B</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
.
.
.
.
<location>
<locationid>10</locationid>
<homeID>21</homeID>
<buildingType>Added</buildingType>
<address>Z</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
</locations>
Wie kann ich bekommen locationID
für die Adresse A
, Wobei etree
.
Hier ist mein Code ,
import urllib2
import lxml.etree as ET
url="url for the xml"
xmldata = urllib2.urlopen(url).read()
# print xmldata
root = ET.fromstring(xmldata)
for target in root.xpath('.//location/address[text()="A"]'):
print target.find('LocationID')
Ausgabe erhalten als None
, Was mache ich hier falsch?
Lösung
Zuallererst Ihre xml
ist nicht wohlgeformt.Sie sollten beim Posten vorsichtiger sein und versuchen zu vermeiden, dass andere Benutzer Ihre Daten reparieren.
Sie können nach dem vorhergehenden Geschwister suchen, z:
import urllib2
import lxml.etree as ET
url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
for target in root.xpath('.//location/address[text()="A"]'):
for location in [e for e in target.itersiblings(preceding=True) if e.tag == "locationid"]:
print location.text
Oder machen Sie es direkt von der xpath
ausdruck, wie:
import urllib2
import lxml.etree as ET
url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
print root.xpath('.//location/address[text()="A"]/preceding-sibling::locationid/text()')[0]
Führen Sie einen von ihnen wie folgt aus:
python2 script.py
Diese Ausbeute:
1
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow