I need to extract from an XML few nodes IF one of them contains keyword. Finally I got to point where I'll have the keywords printed if found. Now is the tricky part (at least for me ;-)). I'll explain it below in more details. XML:
<?xml version="1.0"?>
<ItemSearchResponse xmlns="http://url">
<Items>
<Item>
<ItemAttributes>
<ListPrice>
<Amount>2260</Amount>
</ListPrice>
</ItemAttributes>
<Offers>
<Offer>
<OfferListing>
<Price>
<Amount>1853</Amount>
</Price>
</OfferListing>
</Offer>
</Offers>
<Offers>
<Offer>
<OfferListing>
<Price>
<Amount>1853</Amount>
</Price>
</OfferListing>
</Offer>
</Offers>
<Offers>
<Offer>
<OfferListing>
<Price>
<Amount>1200</Amount>
</Price>
</OfferListing>
</Offer>
</Offers>
</Item>
</Items>
</ItemSearchResponse>
My script prints out the Amount value if found and == 1853. What I actually need is: when 1853 found - the script should extract the whole <Offers>
to new file. I got script running and got stuck. I have really no clue how to get back from <Amount>
and copy the whole <Offers>
group.
Script 1:
import xml.etree.ElementTree as ET
import sys
name = str.strip(sys.argv[1])
filename = str.strip(sys.argv[2])
fp = open("sample.xml","r")
element = ET.parse(fp)
for elem in element.iter():
if elem.tag == '{http://url}Price':
output = {}
for elem1 in list(elem):
if elem1.tag == '{http://url}Amount':
if elem1.text == name:
output['Amount'] = elem1.text
print output
And my output:
python sample1.py '1853' x
{'Amount': '1853'}
{'Amount': '1853'}
The 'x'-thing here is no relevant.
How to get back from <Amount>
and copy the whole <Offers>
group to a new file or just print the thing out. It need to be done with ElementTree.