Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用lxml从xml文件获取值_Python_Python 2.7_Xpath_Xml Parsing_Lxml - Fatal编程技术网

Python 使用lxml从xml文件获取值

Python 使用lxml从xml文件获取值,python,python-2.7,xpath,xml-parsing,lxml,Python,Python 2.7,Xpath,Xml Parsing,Lxml,作为将用户配置存储到数据库的替代方法,我现在选择将这些配置存储在xml文件中。使用lxml,我创建了以下(示例): 提前谢谢 编辑:我不想你们给我完整的解决方案。我找到了这个链接,它显示了我是如何做到这一点的,但我创建了这个帖子,看看是否有比给出的答案更“干净”的东西。另外,我不想使用BeautifulSoup,因为我已经在使用lxml这是基本思想(尚未测试): 返回: Config a is: 10 Config b is: 4 Config c is: true 您是否已经尝试过编写get

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

提前谢谢

编辑:我不想你们给我完整的解决方案。我找到了这个链接,它显示了我是如何做到这一点的,但我创建了这个帖子,看看是否有比给出的答案更“干净”的东西。另外,我不想使用
BeautifulSoup
,因为我已经在使用
lxml

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

返回:

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

您是否已经尝试过编写
getTriggerConfig
?@furins,还没有,我仍在尝试如何获取值。我已经提供了完整的解决方案,抱歉:)但是它非常简短,并且仅基于
lxml
返回:AttributeError:'list'对象没有属性'iterchildren'。我将按预期查看更多infoWork。谢谢!我进行了回滚,以防止在代码中添加注释的外国用户进行最后一次编辑。如果您想在上面的答案中添加注释,而不是答案的原始海报,则必须将其作为注释来完成。@jeff noel编辑是正确的,并解决了答案中的一个错误(我已经提到了从文件解析的可能性,但我忘了说它返回不同类型的对象)。我接受了泰雷兹的编辑并整合了它,以解释为什么需要它。
print getTriggerConfig('trigger_a')

Config a is: 10
Config b is: 4
Config c is: true
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