How do I parse XML in Python ?

How do I parse XML in Python ?

Asked on December 14, 2018 in XML.
Add Comment


  • 3 Answer(s)

    This may your answer:

       The other compatible implementations of the similar API were lxml, and cElementTree in the Python standard library;the content  the ease of programming part depends on the API, which ElementTree defines.

    Then constructing an Element instance e from the XML, with the XML function, or by parsing a file by,

    import xml.etree.ElementTree
    e = xml.etree.ElementTree.parse('thefile.xml').getroot()
    

    or simple code patterns like,

    for atype in e.findall('type'):
      print(atype.get('foobar'))
    

     

    Answered on December 14, 2018.
    Add Comment

    To parse XML in Python:

         The active and forward will be minidom.

    XML:

    <data>
      <items>
        <item name="item1"></item>
        <item name="item2"></item>
        <item name="item3"></item>
        <item name="item4"></item>
      </items>
    </data>
    

    PYTHON:

    from xml.dom import minidom
    xmldoc = minidom.parse('items.xml')
    itemlist = xmldoc.getElementsByTagName('item')
    print(len(itemlist))
    print(itemlist[0].attributes['name'].value)
    for s in itemlist:
      print(s.attributes['name'].value)
    

    OUTPUT:

    4
    item1
    item1
    item2
    item3
    item4

    Answered on December 14, 2018.
    Add Comment

    Follow the code:

         Work with BeautifulSoup method

    from bs4 import BeautifulSoup
    x="""<foo>
      <bar>
        <type foobar="1"/>
        <type foobar="2"/>
      </bar>
    </foo>"""
     
    y=BeautifulSoup(x)
    >>> y.foo.bar.type["foobar"]
    u'1'
     
    >>> y.foo.bar.findAll("type")
    [<type foobar="1"></type>, <type foobar="2"></type>]
     
    >>> y.foo.bar.findAll("type")[0]["foobar"]
    u'1'
    >>> y.foo.bar.findAll("type")[1]["foobar"]
    u'2'
    
    Answered on December 14, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.