繁体   English   中英

使用lxml从xml文件获取值

[英]Get values from xml file using lxml

作为将用户配置存储到数据库的替代方法,我现在选择将那些配置存储在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

提前致谢。

编辑:我不希望你们给我完整的解决方案。 我找到了此链接“ 如何在Python中获取XML标记值”,该链接显示了我的操作方法,但是我创建了此文章,以查看是否有比给出的答案“更干净”的东西。 另外,由于我已经在使用lxml所以我不想使用BeautifulSoup

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM