1

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.

Community
  • 1
  • 1
thclpr
  • 5,778
  • 10
  • 54
  • 87

1 Answers1

2

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
furins
  • 4,979
  • 1
  • 39
  • 57
  • returned: AttributeError: 'list' object has no attribute 'iterchildren' . I'll check out more info – thclpr Dec 30 '13 at 13:21
  • Work as intended. Thanks a lot! – thclpr Dec 30 '13 at 13:51
  • I did a rollback to prevent the last edit from a foreign user who added a comment within the code. If you want to add notes to the answer above and aren't the original poster of the answer, it must be done as a comment. – Jeff Noel Dec 30 '13 at 14:27
  • @jeff-noel the edit was correct and solved an error in the answer (I already mentioned the possibility to parse from a file, but I forgot to say that it returns a different type of object). I accepted Thales edit and integrated it to explain why it is needed. – furins Dec 30 '13 at 14:30