1

I have problem with extracting data from a xml file what contains the lxml. I've tried to extract data with use of lxml library but i have no output at all.

from lxml import etree 
tree = etree.parse("ifm-00028A-20170711-IODD1.1.xml")
root = tree.getroot()
levels = root.findall('DeviceIdentity', root.nsmap)
for DeviceIdentity in levels:
data_1 = int(DeviceIdentity.find('deviceId').text)
print(data_1)

[IODD][1]

I need for example get the value from the vendorId and deviceId

Thanks for help !

Sample of the xml file https://i.stack.imgur.com/Ih4Tk.png

Pawel12345
  • 13
  • 3
  • 4
    Hi, welcome to stackoverflow.com. Please avoid pasting code/text as images. It makes it impossible for others to search. Please take some time to read the [help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic). Also please [take the tour](http://stackoverflow.com/tour) and read about [how to ask good questions](https://stackoverflow.com/help/how-to-ask). Lastly please read [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Spangen Nov 15 '18 at 11:30

1 Answers1

1

There are two bugs here.

First, findall findall only searches the immediate descendants of an element if it is given a tag name. You can use XPath expressions to search deeper. So your findall should be

levels = root.findall('.//DeviceIdentity', root.nsmap)

Then, deviceId is an attribute. You should be able to find it in the element's attrib dictionary. Assuming the rest of your code is correct, it would look something like this:

for DeviceIdentity in levels:
    data_1 = int(DeviceIdentity.attrib['deviceId'])
    print(data_1)

(In future questions, it would have been helpful to include the sample XML as text, and to be more specific than "no output at all")

  • so if the deviceId is the attribute then what is the value of the deviceId? '650' how can i get just this value ? – Pawel12345 Nov 15 '18 at 14:52
  • @Pawel12345 `DeviceIdentity.attrib['deviceId']`, as shown. –  Nov 15 '18 at 14:53
  • 1
    @Pawel12345 If this answer was useful, please consider upvoting or accepting it using the arrow and check mark to the left of the answer. –  Nov 15 '18 at 16:36