Reading XML file and fetching its attributes value in Python

后端 未结 7 694
情歌与酒
情歌与酒 2020-12-03 15:56

I have this XML file:


  virtual bug
  66523dfdf555dfd
  
          


        
7条回答
  •  青春惊慌失措
    2020-12-03 16:34

    Here's an lxml snippet that extracts an attribute as well as element text (your question was a little ambiguous about which one you needed, so I'm including both):

    from lxml import etree
    doc = etree.parse(filename)
    
    memoryElem = doc.find('memory')
    print memoryElem.text        # element text
    print memoryElem.get('unit') # attribute
    

    You asked (in a comment on Ali Afshar's answer) whether minidom (2.x, 3.x) is a good alternative. Here's the equivalent code using minidom; judge for yourself which is nicer:

    import xml.dom.minidom as minidom
    doc = minidom.parse(filename)
    
    memoryElem = doc.getElementsByTagName('memory')[0]
    print ''.join( [node.data for node in memoryElem.childNodes] )
    print memoryElem.getAttribute('unit')
    

    lxml seems like the winner to me.

提交回复
热议问题