我正在开发一个 python 程序来保持储藏室的库存。在 XML 文档中将保留碳粉量,我希望我的 python 程序能够添加、删除和显示不同打印机和不同颜色的碳粉量。
我的 XML 看起来像这样:
<?xml version="1.0"?>
<printer>
<t id="095205615111"> <!-- 7545 Magenta -->
<toner>7545 Magenta Toner</toner>
<amount>3</amount>
</t>
<t id="095205615104"> <!-- 7545 Yellow -->
<toner>7545 Yellow Toner</toner>
<amount>7</amount>
</t>
</printer>
id 是我们用于库存的条形码中的编号。
到目前为止,我希望我的程序使用这些步骤:
检查 id 是否存在(id 值是我的 python 程序中的一个变量,从 txt 文件中的内容管道传输)
将xml文档中的amount值改为+1或-1
无论我尝试什么,它都无法完全奏效。您对我可以使用什么有什么建议吗?
请您参考如下方法:
Check if the id exist
您可以通过构造一个检查 @id 属性值的 XPath 表达式来解决这个问题。
Change the value of amount in the xml-document to +1 or -1
一旦您通过特定的id 找到了t 节点,您就可以使用find() 来定位内部的amount 节点。然后,您可以获得 .text,将其转换为整数,更改它,转换回字符串并设置 .text 属性。
工作示例:
from lxml import etree
data = """<?xml version="1.0"?>
<printer>
<t id="095205615111"> <!-- 7545 Magenta -->
<toner>7545 Magenta Toner</toner>
<amount>3</amount>
</t>
<t id="095205615104"> <!-- 7545 Yellow -->
<toner>7545 Yellow Toner</toner>
<amount>7</amount>
</t>
</printer>"""
root = etree.fromstring(data)
toner_id = "095205615111"
# find a toner
results = root.xpath("//t[@id = '%s']" % toner_id)
if not results:
raise Exception("Toner does not exist")
toner = results[0]
# change the amount
amount = toner.find("amount")
amount.text = str(int(amount.text) + 1)
print(etree.tostring(root))
