[verb ない-form 〜ない → 〜] + んがため(に) [verb ない-form 〜ない → 〜] + んがための + [noun] する → せんがため(に)
んがために means "in order to", with a strong sense of will behind the goal. It replaces the ない of the ない-form, so 勝たない gives かた勝たんがために and 生きない gives いき生きんがために; する becomes せんがために. It is a literary form, found in essays, speeches and fiction.
The に is optional, as the third example shows. The ん is an old ending meaning "would", not a negative, and が is an old form of の, so the pattern reads "for the sake of doing".
Before a noun, the form is んがための.