Videos and images posted online by witnesses showed bodies spread along alleyways.
The suspect, identified by the surname Zhao, reportedly confessed and was being held Friday night local time.
Seven people were killed. Last February, a man stabbed a woman to death and injured 12 other people at a shopping mall in Beijing.
In January 2017, a man barged into a kindergarten classroom in China's southern Guangxi Zhuang region with a kitchen knife and stabbed 11 children.
Chinese police reported the motive for the killing of high school students in Shaanxi province.
The attack revived fears in China about school safety, a perennial concern among parents. Authorities have also called in specialists to aid the wounded.
Violent crime has risen in recent decades as the country's economy has boomed and the wealth equality gap has increased. China's Ministry of Education responded to those events by ordering schools to beef up security and bar strangers from going on campuses. Material to make a homemade explosive device was found in the home.