Answer the question
In order to leave comments, you need to log in
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>
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
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
['Masha']
[Finished in 0.1s]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question