There are several overnight trains each day between Shanghai and Beijing. Unless you will be travelling around the beginning or end of the Chinese New Year (Jan. 29 and through the following week), you can get tickets once you arrive in Shanghai. Pre-booking would cost more.
I've never taken the two-berth cabin. The four-berth soft sleeper and even hard sleeper on those trains are very nice, though of course you must share those with other passangers.
The train costs 921 RMB for the lower bunk and 881 RMB for the upper bunk. IMO I'd just take the normal 4-person soft sleeper for 478 (upper) and 499 (lower) RMB instead. The tickets go on sale 20 days in advance so it'd be wise to buy in advance (ie when you first arrive in Shanghai); besides, this is a peak travel period for the locals (Chinese New Year).
I forgot to mention that buying in advance (not pre-booking via agent, that's different) doesn't cost any more money than what's stated on the ticket. I know, cos I've just helped to buy tickets for 2 friends of mine!