使用lxml从xml文件中获取值

时间:2013-12-30 12:58:46

标签: python python-2.7 xpath xml-parsing 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

提前致谢。

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

1 个答案:

答案 0 :(得分:2)

这是基本的想法(尚未经过测试测试):

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