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

后端 未结 2 1565
执念已碎
执念已碎 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
    
    0 讨论(0)
  • 2021-01-20 20:40
    import xml.etree.ElementTree as etree
    
    xmlD = etree.parse('xmlTest.xml')
    root = xmlD.getroot()
    
    for child in root:
        for children in child:
            print(children.text)
    
    0 讨论(0)
提交回复
热议问题