簡體   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