Alter namespace prefixing with ElementTree in Python

前端 未结 2 1261
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 03:18

By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it\'s namespace URI in Clark\'s Notation:

         


        
2条回答
  •  臣服心动
    2020-12-31 03:44

    You don't specifically need to use iterparse. Instead, the following script:

    from cStringIO import StringIO
    import xml.etree.ElementTree as ET
    
    NS_MAP = {
        'http://www.red-dove.com/ns/abc' : 'rdc',
        'http://www.adobe.com/2006/mxml' : 'mx',
        'http://www.red-dove.com/ns/def' : 'oth',
    }
    
    DATA = '''
    
      
        
      
      
        
      
      
        
      
    '''
    
    tree = ET.parse(StringIO(DATA))
    some_node = tree.getroot().getchildren()[1]
    print ET.fixtag(some_node.tag, NS_MAP)
    some_node = some_node.getchildren()[0]
    print ET.fixtag(some_node.tag, NS_MAP)
    

    produces

    ('mx:Style', None)
    ('oth:style2', None)
    

    Which shows how you can access the fully-qualified tag names of individual nodes in a parsed tree. You should be able to adapt this to your specific needs.

提交回复
热议问题