4
You have 23 days.
Beijing (4 days) -- bus -- Datong (1 day) -- bus (via Taiyuan) -- Pingyao (2 days) -- overnight train -- Xi'an (2 days) -- bus/train -- Luoyang (1 day) -- bus -- Shaolin (2 days) -- bus -- Luoyang (transit only) -- overnight train -- Shanghai (4 days) -- train (1 day via Guilin) -- Yangshuo (4 days) -- train/bus (via Guilin) -- Nanning (2 days) -- move on to Hanoi
Ok that seems to be the gist of your itinerary. Here're my suggestions.
I think you should go back to Luoyang after Shaolin Temple in order to get a sleeper train to Shanghai (train 1657/1660, 1956--1247). Reason being that although Zhengzhou would have more possibilities, almost all the trains that pass by Zhengzhou are "stopover" trains which don't originate in Zhengzhou. It would be difficult to get a sleeper ticket for those trains, and I would expect it to be impossible at short notice. Whereas if you start from Luoyang, you could try for the ticket as soon as you arrive in Luoyang, and the train that I named originates in Luoyang so you have a better chance.
2 days for Shaolin is a little excessive. I think 1 day would be enough, unless you're seeing Zhongyue Temple in Dengfeng as well.
1 day in Datong isn't enough if you want to see both Yungang Grottoes and Hanging Monastery on public transport. It's adequate if you're taking a tour.
Also, remember that Beijing -- Datong and Datong -- Pingyao both take up half a day each. Remember to factor in the travel time. Same thing for Shanghai -- Guilin which takes about 1 entire day.
For Pingyao -- Xi'an, get a guesthouse to pre-buy your train tickets.
You might consider going on a sidetrip for Shanghai since you have 4 days there.
Why do you need 2 days in Nanning? Unless you're trying to get your Vietnam visa issued there?
Personally I think this is lacking a little for scenery as Yangshuo seems to be the only destination for that. This is actually a little heavier on history/culture. I would try to put in Huangshan, but you'll probably need to replace something. Maybe you could consider skipping Luoyang and Shaolin Temple and instead fly from Xi'an to Huangshan. There's no direct train between these 2 destinations.
Cheers!