【问题标题】:Python lxml finding element by id-tagPython lxml通过id-tag查找元素
【发布时间】:2017-05-02 09:32:32
【问题描述】:

我正在开发一个用于保存储藏室库存的 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

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

【问题讨论】:

  • 发布您的代码,无论您尝试了什么

标签: python xml xml-parsing lxml


【解决方案1】:

检查id是否存在

您可以通过构造一个检查@id 属性值的XPath 表达式来解决这个问题。

将 xml 文档中的 amount 值更改为 +1 或 -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))

【讨论】:

  • @Diego 没问题。下次尝试发布您尝试过的东西 - 这会引起更多关注并帮助您更好地了解您遇到的问题。此外,请考虑接受解决该主题的答案。谢谢。
【解决方案2】:

您也可以使用lxml.objectify 来处理它,这样可以更轻松地处理数据类型:

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

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2011-10-16
    • 2015-06-05
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2020-07-20
    • 2018-10-20
    相关资源
    最近更新 更多