Python Lxml (objectify): Checking whether a tag exists

后端 未结 4 1374
后悔当初
后悔当初 2021-02-02 11:48

I need to check whether a certain tag exists in an xml file.

For example, I want to see if the tag exists in this snippet:

 
4条回答
  •  感情败类
    2021-02-02 11:55

    If your document tends to be relatively short you can iterate over all children of

    looking for tags matching your set of variable names:

    tree = lxml.etree.fromstring(DATA)
    NAMES = set(['elem1', 'elem3'])
    for node in tree.iterchildren():
        if node.tag in NAMES:
            print 'found', node.tag
    

    Or you can search for each variable name one at a time:

    for tag in ('elem1', 'elem3'):
        if tree.find(tag) is not None:
            print 'found', tag
    

提交回复
热议问题