Under the linear elastic limit, one may do the following steps to get the strain energy:
1) calculate the total energy of an 1-D system at equilibrium state (i.e., strain = 0.0)
2) apply a small strain (e.g., uniaxial) to an 1-D system. That is to say, the length of 1-D system is elongated or shorten.
3) calculate the total energy of the 1-D system with a small finite strain.
4) the strain energy is obtained by the difference between the total energies in the 3)-rd and 1)-st steps.