speedyrazor
speedyrazor

Reputation: 3205

Python lxml - find tag block ammend

I have the below xml which I have opened and parsed and I now need to find the specific product block with the territory 'IE' and then amend its 'cleared_for_sale' and 'wholesale_price_tier' values, but am unsure how to do it. Heres what doesnt work:

a = 0
territory = "IE"
for products22 in tree.xpath("//video/products/product"):
    node_video_temp = tree.xpath('//video/products/product')[a]
    if root.iterfind(node_video_temp, territory):
        ## Update the values ##
    a +=1

Heres the xml:

<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://apple.com/itunes/importer" version="film5.0">
    <video>
        <products>
            <product>
                <territory>GB</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
            <product>
                <territory>IE</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
            <product>
                <territory>US</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
        </products>
    </video>
</package>

Upvotes: 1

Views: 129

Answers (1)

alecxe
alecxe

Reputation: 473753

You can make an xpath expression to get all products where territory is IE:

//product[territory = "IE"]

But, you need to handle an empty namespace here:

from lxml import etree

data = """<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://apple.com/itunes/importer" version="film5.0">
    <video>
        <products>
            <product>
                <territory>GB</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
            <product>
                <territory>IE</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
            <product>
                <territory>US</territory>
                <cleared_for_sale>true</cleared_for_sale>
                <wholesale_price_tier>1</wholesale_price_tier>
            </product>
        </products>
    </video>
</package>
"""

ns = {"x": "http://apple.com/itunes/importer"}
territory = 'IE'

root = etree.fromstring(data)
for product in root.xpath('//x:product[x:territory = "%s"]' % territory, namespaces=ns):
    print product.findtext('x:cleared_for_sale', namespaces=ns)
    print product.findtext('x:wholesale_price_tier', namespaces=ns)

Prints cleared_for_sale and wholesale_price_tier for territory="IE":

true
1

Upvotes: 1

Related Questions