How to parse some optional elements present in XML document using python script?
<p>I have xml document collected from below link</p>

<p><a href="http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&amp;hc=100" rel="nofollow">http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&amp;hc=100</a></p>

<p>I am parsing <code>Title</code>, <code>Abstract</code>, <code>Author</code> and <code>Affiliation</code> from this xml document and creating separate text files. Some documents have abstract element but few don't have. I have written a python script which is used to parse required fields but do not work if any of the above mentioned element is not present. plz suggest any possible way to skip such docs:) </p>

<pre><code>import xmltodict
for i in range (1000):
    with open('C:/Python27/Major Project/2000 ipsSearch.jsp.xml') as fd:
        fout = open(str(i)+".txt","w")   ## Flush old records from output file
        doc = xmltodict.parse(fd.read())
        w = doc['root']['document'][i]['rank']
        x = doc['root']['document'][i]['title']
        y = doc['root']['document'][i]['abstract']
        z = doc['root']['document'][i]['authors']
        a = doc['root']['document'][i]['affiliations']
        fout.write(str(w)+"\n"+str(x)+" "+str(y)+"\n"+str(z)+"\n"+str(a))
</code></pre>

<p>getting error when there is no <code>abstract</code> element present in any <code>document</code>.</p>

<p>Play the safe way - check if the element is present first, otherwise assign an empty string.</p>

<p>Now, since the  parsed XML appears as dictionary you can use the <code>in</code> operator to check for that, and the ternary <code>if...else</code> operator to default the cases where you cant find an <code>abstract</code>:</p>

<pre><code>    ...
    y = doc['root']['document'][i]['abstract'] if 'abstract' in doc['root']['document'][i] else ''
    z = doc['root']['document'][i]['authors'] if 'authors' in doc['root']['document'][i] else ''
    ...
</code></pre>

<p>Same goes for all elements.</p>

python xml parsing