简体   繁体   中英

Python - Append “None” to Array if XML element is not in Record

I am using lxml in Python to parse an XML file. The file contains records with elements. The first element is always there. However, the other elements are not always available in each record. If an element is not there I want to add a "None" entry to Elementx list. When I do that each element list has the same size and I can easily append new values in the for loop when these are not present in the previous list. How can i append a "None" value in the element list when the element is not available in the record?

The code looks like this:

Element1_list = []
Element2_list = []
.
.
ElementN_list = []

  def repeat():
    xmlfile = urllib2.urlopen("link.xml").read()
    root = lxml.etree.fromstring(xmlfile)

    # Grabbing the elements from the XML file, list are here not equal in size
    Element1 = root.xpath('//Record/Element1/text()')
    Element2 = root.xpath('//Record/Element2/text()')
    .
    .
    ElementN = root.xpath('//Record/ElementN/text()')

    i = 0
    for element in Element1: 
      if element not in Element1_list: 
        Element1_list.append(Element1[i])
        Element2_list.append(Element2[i])
        .
        .
        ElementN_list.append(ElementN[i])
    i = i + 1
  repeat()

repeat()

Thanks in advance.

you can try to use if else.

lst = []
ele1,ele2 = None,'Something'
lst.append( ele1 if ele1 else None )
lst.append( ele2 if ele2 else None )
print lst 
[None, 'Something']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM