python - 使用 lxml 从 xml 文件获取值

标签 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

最佳答案

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

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

关于python - 使用 lxml 从 xml 文件获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20840075/

相关文章:

python - Mac OS X 10.10 合并错误

xml - XSLT:替换两个节点之间的文本

java - Xpath - 评估函数返回 javax.xml.transform.TransformerException

python - 在 Python 中查找字符串中所有出现的开始和结束位置

python - ipdb 和方法文档

sql-server - Python - pyodbc 使用参数名称调用存储过程

xml - 基于标签名称及其值的知识计算 XML 文档的 XPath

python - Configparser 整数

Python 模块内的 Javascript 问题

google-app-engine - 谷歌眼镜Python快速入门