Python Lxml (objectify): Checking whether a tag exists

后端 未结 4 1330
后悔当初
后悔当初 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 <main> 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
    
    0 讨论(0)
  • 2021-02-02 12:02

    hasattr() works for this:

    if hasattr(root, 'elem1'):
        foo = root.elem1
    
    0 讨论(0)
  • 2021-02-02 12:12

    Edit: updated answer for sample file.

    I'm assuming you want to search each asset for certain tags. If so, the following worked for me:

    import lxml.objectify
    
    # Parse the file.
    tree = lxml.objectify.parse('sample.xml')
    root = tree.getroot()
    
    # Which elements to find.
    to_find = set(['presence/faction', 'presence/value', 'fake'])
    
    # Go through each asset in the document.
    for asset in root.findall('asset'):
        # Check for each element. 
        for name in to_find:
            node = asset.find(name)
            if node is not None:
                print 'Found %s, its value is %s' % (name, node)
            else:
                print 'Unable to find %s' % name
    

    The output was:

    Found presence/value, its value is -1000.0
    Found presence/faction, its value is Dvaered
    Unable to find fake
    Found presence/value, its value is 100.0
    Found presence/faction, its value is Empire
    Unable to find fake
    
    0 讨论(0)
  • 2021-02-02 12:14

    Assume you want to get elem2's value, you can use xpath to find it.

    tree = etree.parse(StringIO(htmlString), etree.HTMLParser()).getroot()
    youWantValue = tree.xpath('/main/elem2')[0].text
    
    0 讨论(0)
提交回复
热议问题