G
G
gadzhi152016-04-11 20:25:18
Python
gadzhi15, 2016-04-11 20:25:18

LXML in Python? How to pass a variable?

There is an XML file like this:

<employees>
  <employee>
    <id>1</id>
    <name>Oleg</name>
  </employee>
  <employee>
    <id>2</id>
    <name>Masha</name>
  </employee>
</employees>

Using Python 2.7 and the lxml library, I need to display the value of the name tag by the desired id.
The whole problem lies in the fact that the desired id is stored in a variable. And in the tree.xpath method, you can specify the desired value, but not the variable that contains the value? How to implement the code in this case?
tree = etree.parse('test.xml')
id = "2"

event_name2 = tree.xpath(r'.//id[text() = "2"]'r'/../name/text()')
name = ''.join(event_name2).encode('utf-8')
print name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2016-04-11
@gadzhi15

Why not:

# -*- coding: utf-8 -*-
from lxml import etree
import StringIO

test ="""<employees>
  <employee>
    <id>1</id>
    <name>Oleg</name>
  </employee>
  <employee>
    <id>2</id>
    <name>Masha</name>
  </employee>
</employees>"""

fl = StringIO.StringIO()
fl.write(test)
fl.seek(0)

tree = etree.parse(fl)

your_var = 2

event_name2 = tree.xpath(r'.//id[text() = "{id}"]/../name/text()'.format(id=your_var))
print event_name2

will bring out
['Masha']
[Finished in 0.1s]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question