Python lxml按id标记查找元素

2024-05-20 18:43:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个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是我们用于库存的条形码中的编号。

到目前为止,我希望我的程序使用以下步骤:

  1. 检查该id是否存在(id值是我的python程序中的一个变量,从txt文件的内容中导出)

  2. 将xml文档中amount的值更改为+1或-1

无论我尝试什么,都不会完全奏效。你对我能用什么有什么建议吗?


Tags: 文档程序id数量库存打印机xml色调
2条回答

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))

您还可以使用^{}来接近它,这将使处理数据类型更容易:

from lxml import objectify, 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 = objectify.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
toner.amount += 1

# dump the tree object back to XML string
objectify.deannotate(root)
etree.cleanup_namespaces(root)
print(etree.tostring(root))

注意,金额变更是如何实施的:

toner.amount += 1

相关问题 更多 >