Using XPATH in python etree to select node with out a specific attribute

后端 未结 2 1566
执念已碎
执念已碎 2021-01-20 20:10

Following is my xml file contents,



    
        1
         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-20 20:35

    ElementTree only supports a subset of XPath 1.0. See https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support. Functions such as not() or count() do not work.

    Here is how you can select neighbor elements that don't have a direction attribute without using XPath:

    tree = ET.parse(fileName)
    
    for n in tree.iter('neighbor'):  
        if not(n.get('direction')):  # If the element has no 'direction' attribute...
            print n.get('name')      # then print the value of the 'name' attribute
    

提交回复
热议问题