There are two crossings in Vietnam which involve trains, both with China, but only one of them has a train on each side of the border. The Dong Dang crossing, just over 160km from Hanoi can be reached by train from Hanoi, with the trainline continuing on into China, running north eventually to Beijing. There is a thrice weekly train between Hanoi and Beijing. The Chinese side of the border is the town of Ping Xian. While you can buy a through ticket to Beijing in Hanoi, it is cheaper just to buy the ticket to Dong Dang, take a xe om over the border and buy a new ticket in China (at a reduced rate).
The second train crossing is at Lao Cai (near Sapa) in northwest Vietnam, the Chinese town of Hekou is on the other side of the border. There is no train on the Chinese side though, so you need to arrange alternative transport onwards into China.