【问题标题】:Get values from xml file using lxml使用 lxml 从 xml 文件中获取值
【发布时间】:2014-01-17 08:53:10
【问题描述】:

作为将用户配置存储到数据库的替代方法,我现在选择将这些配置存储在 xml 文件中。使用lxml,我创建了以下(示例):

<root>
  <trigger name="trigger_a">
    <config_a>10</config_a>
    <config_b>4</config_b>
    <config_c>true</config_c>
  </trigger>
  <trigger name="trigger_b">
    <config_a>11</config_a>
    <config_b>5</config_b>
    <config_c>false</config_c>
  </trigger>
</root>

所以我的意图是,给出我想要的触发器名称,以获取相关配置。像这样的东西,例如:

print getTriggerConfig('trigger_a')

Config a is: 10
Config b is: 4
Config c is: true

提前致谢。

编辑:我不希望你们给我完整的解决方案。我找到了这个链接How to get XML tag value in Python,它显示了我是如何做到的,但我创建了这篇文章,看看是否有比给出的答案“更干净”的东西。另外,我不想使用BeautifulSoup,因为我已经在使用lxml。

【问题讨论】:

  • 你已经尝试写getTriggerConfig了吗?
  • @furins ,还没有,我仍在尝试发现如何获取值
  • 我已经提供了一个完整的解决方案,抱歉 :) 但它很短并且仅基于 lxml

标签: python python-2.7 xpath xml-parsing lxml


【解决方案1】:

这是基本思想(尚未测试已测试):

from lxml import etree

f = """<root>
  <trigger name="trigger_a">
    <config_a>10</config_a>
    <config_b>4</config_b>
    <config_c>true</config_c>
  </trigger>
  <trigger name="trigger_b">
    <config_a>11</config_a>
    <config_b>5</config_b>
    <config_c>false</config_c>
  </trigger>
</root>"""

tree = etree.XML(f)
# uncomment the next line if you want to parse a file
# tree = etree.parse(file_object)

def getTriggerConfig(myname):
   # here "tree" is hardcoded, assuming it is available in the function scope. You may add it as parameter, if you like.
   elements = tree[0].xpath("//trigger[@name=$name]/*", name = myname)
   # If reading from file uncomment the following line since parse() returns an ElementTree object, not an Element object as the string parser functions.
   #elements = tree.xpath("//trigger[@name=$name]/*", name = myname)
   for child in elements:
       print("Config %s is: %s"%(child.tag[7:], child.text))

用法:

getTriggerConfig('trigger_a')

返回:

Config a is: 10
Config b is: 4
Config c is: true

【讨论】:

  • 返回:AttributeError: 'list' object has no attribute 'iterchildren' 。我会查看更多信息
  • 按预期工作。非常感谢!
  • 我进行了回滚以防止在代码中添加评论的外国用户进行最后一次编辑。如果您想在上面的答案中添加注释并且不是答案的原始发布者,则必须作为评论完成。
  • @jeff-noel 编辑是正确的并解决了答案中的错误(我已经提到了从文件解析的可能性,但我忘了说它返回了不同类型的对象)。我接受了泰雷兹的编辑并整合它来解释为什么需要它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2020-07-12
  • 2023-03-29
相关资源
最近更新 更多