Python lxml-查找标记块ammend
我已经打开并解析了下面的xml,现在我需要找到带有区域“IE”的特定产品块,然后修改其“cleared_for_sale”和“Wholesal_price_tier”值,但不确定如何执行。以下是不起作用的:Python lxml-查找标记块ammend,python,xml,xml-parsing,tags,lxml,Python,Xml,Xml Parsing,Tags,Lxml,我已经打开并解析了下面的xml,现在我需要找到带有区域“IE”的特定产品块,然后修改其“cleared_for_sale”和“Wholesal_price_tier”值,但不确定如何执行。以下是不起作用的: a = 0 territory = "IE" for products22 in tree.xpath("//video/products/product"): node_video_temp = tree.xpath('//video/products/product')[a]
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
以下是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>
国标
真的
1.
即
真的
1.
美国
真的
1.
您可以创建一个xpath表达式,以获取territory
所在的所有产品IE
:
//product[territory = "IE"]
但是,您需要在这里:
如何修改值而不是打印product.findtext?@speedyrazor您的意思是更改元素的文本值吗?是的,例如,将批发价格层值更改为7。@speedyrazor应该是
product.find('x:wholesale\u price\u tier')。text='7'
。然后,您需要转储树以查看更改。抱歉,在更新之前,现在无法检查批发价格层是否存在。
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)
true
1