简体   繁体   English

Python-如果XML元素不在记录中,则将“ None”追加到数组

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

I am using lxml in Python to parse an XML file. 我在Python中使用lxml解析XML文件。 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. 如果没有元素,我想在Elementx列表中添加一个“无”条目。 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. 当我这样做时,每个元素列表都具有相同的大小,并且当前一个列表中不存在新值时,我可以轻松地在for循环中附加这些新值。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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