在python中使用Etree解析XML配置文件 [英] parsing XML configuration file using Etree in python

查看:413
本文介绍了在python中使用Etree解析XML配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我使用lxml etree解析以下原型的配置文件.我尝试与事件,与tostring元素.不幸的是,我不需要文本,但是

Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring. Unfortunately I don't need the text, but the XML between

<template name> 
   <config>
 </template> 

给定属性的

.

for a given attribute.

我从这段代码开始,但是在搜索属性时遇到关键错误,因为它是从开始扫描的

I started with this code, but get a key error while searching for the attribute since it scans from start

config_tree = etree.iterparse(token_template_file)
for event, element in config_tree:

    if element.attrib['name']=="ad auth":
        print ("attrib reached. get XML before child ends")

由于我是XML和python的新手,所以我不确定该怎么做.这是配置文件:

Since I am a newbie to XML and python, I am not sure how to go about it. Here is the config file:

<Templates>

  <template name="config1">

    <request>

      <password>pass</password>

      <userName>username</userName>

      <appID>someapp</appID>

    </request>

  </template>

  <template name="config2">

    <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

  </template>

</Templates>

提前谢谢!

预期输出:

假设用户请求config2-,则输出应类似于:

Say the user requests the config2- then the output should look like:

   <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

(我使用httplib2将此XML发送到服务器进行初始身份验证)

(I send this XML using httplib2 to a server for initial authentication)

最终代码:

感谢FC和Constantnius.这是最终代码:

thanks to FC and Constantnius. Here is the final code:

    config_tree = etree.parse(token_template_file)
    for template in config_tree.iterfind("template"):

        if template.get("name") == "config2":
            element = etree.tostring(template.find("request"))

            print (template.get("name"))
            print (element)  

输出:

     config2

    <request>

         <password>pass1</password>

          <userName>username1</userName>

          <appID>someapp</appID>

    </request>

推荐答案

您可以尝试遍历XML中的所有template元素,并使用以下代码解析它们:

You could try to iterate over all template elements in the XML and parse them with the following code:

for template in root.iterfind("template"):
    name = template.get("name")
    request = template.find(requst)
    password = template.findtext("request/password")
    username = ...
    ...
    # Do something with the values

这篇关于在python中使用Etree解析XML配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆