Buy a train ticket at the railway station
You can buy tickets yourself at the station reservation office, remember to take your passport with you. In big cities such as Beijing or Shanghai you should use the special reservations office for foreigners.
Reservations for the best Z-category express trains open 20 days (or in some cases 10 days) before departure, reservations for most other trains open up to 10 days before departure, assuming the train you want starts its journey at that station.
If the train you want starts its journey somewhere else and calls at your boarding station already well into its journey, tickets may only be available 2 days before departure. The rules vary by city..!
You can generally only book a train journey at the station where your journey starts, so (for example) the reservations office at Shanghai can sell you a Shanghai-Beijing ticket but not a Beijing-Xian ticket. Berths are best booked at least 2-3 days in advance, apart from peak periods (the Spring Festival, May Day 1st May, National Day 1st October) when they should be booked as soon as reservations open.
In Beijing, you can buy tickets at Beijing Main station (metro Bejingzhan), or Beijing West station (called Beijing Xi or Xizhan, metro Junshibowuguan). At Beijing Main station, the ticketing office for foreigners is on the north west corner of the 1st floor, accessed via the soft seat waiting room. It is open 05:30-07:30, 08:00-18:30, 19:00-23:00. Only domestic Chinese tickets are sold, no international tickets. At Beijing West station, the foreigners ticketing office is on the 2nd floor, open 24 hours.

How to buy a train ticket in advance?
If you want to book a Chinese train in advance from outside China, you can do this with several agencies, including Sinoway Travel. Tickets cannot be posted abroad, but can be delivered to your hotel in China to be picked up when you get there. This will cost more than you’d pay at the ticket office, but if you really need to be on a particular train on a particular date, it can be worth booking ahead, especially at peak times, such as around the time of the the Spring Festival, 1st May, or 1st October.
What is the D31 10-hour Beijing-Shanghai train?
Train Number: D31, Running time: 9 hours and 59 minutes, From Beijing to Shanghai Leaving Beijing at 10:50 every day, and arrives in Shanghai on 20:49. The distance is 1463 km.