简体   繁体   中英

Get values from xml file using lxml

As an alternative to store user configs to database, I'm choosing now to store those configs inside a xml file. Using lxml , I created the following (example):

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

So my intention is, giving the trigger name I would like, to get the related config. Something like this, as an example:

print getTriggerConfig('trigger_a')

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

Thanks in advance.

EDIT: I dont want you guys to give me full solution. I found this link How to get XML tag value in Python which shows how I do it, but I created this post to see if there is something "cleaner" than the answer given. Also, I don't want to use BeautifulSoup since I'm already using lxml .

this is the basic idea ( yet untested tested):

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))

usage:

getTriggerConfig('trigger_a')

returns:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM