Skip to content
Advertisement

How to extract element from two similar tags in one code?

I am trying to extract year from multiple xml files. Initially, the xml files are as follows,

JavaScript

I used

JavaScript

It had worked well. But in some xml files the tag is changed to TaxPeriodEndDate

JavaScript

I tried to revise the code to

JavaScript

It did not work. No error message, but no output. Any suggestion is highly appreciated. Thank you.

Advertisement

Answer

The support for xpath in ElementTree is very limited. The union operator (|) doesn’t appear to work and other options, like using the self:: axis or name()/local-name() in a predicate, aren’t supported.

I think your best bet is to use a try/except…

JavaScript

If you can switch to lxml, your original attempt with the union operator will work with a few small changes (mainly use xpath() instead of find() and use the namespaces keyword arg)…

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement