stchris / untangle

Converts XML to Python objects
MIT License
612 stars 83 forks source link

How to determine if a element exists #37

Closed clviper closed 7 years ago

clviper commented 7 years ago

Hi there. I noticed that there was already two issues regarding this topic (#27 and #28) but they were closed without any additional information.

Is there any implemented method to do that? I did not noticed that in the source code.

Currently I have a ugly workaround implemented that is to convert the element to str and then use .find() to determine if the target element exists.

Thank you. And good work with untangle.

stchris commented 7 years ago

Hello @clviper ,

there's no straightforward way to do that right now, so a workaround is the only way to go. Maybe using dir to get a list is somewhat more elegant, even if not more efficient:

>>> x = untangle.parse('<doc><node-with-title><title>test</title></node-with-title><node-no-title></node-no-title></doc>')
>>> dir(x.doc.node_with_title)
[u'title']
>>> dir(x.doc.node_no_title)
[]
>>> 'title' in dir(x.doc.node_with_title)
True
>>> 'title' in dir(x.doc.node_no_title)
False

I hope this helps! And thank you for the compliment 👍