Dirac semimetal phase and switching of band inversion in XMg2Bi2 (X = Ba and Sr)