To understand the environmental quality and heavy metal(loid) pollution of farmlands in Shangdan Valley, the contents of macroelements (Na, K, Si, Mg, Ca, Al, Fe, Ti, P, S, Cl, Br) and heavy metal(loid)s (Cu, Pb, Zn, Mn, Ni, V, Co, Cr, As) were surveyed by the X-ray fluorescence method. The pollution degree and ecological risk of the heavy metal(loid)s were judged by the Nemerow synthetic pollution index, geo-accumulation index, and potential ecological risk index, and their sources were identified by the multivariate statistic method. The mean contents of nine heavy metal(loid)s in Shangdan Valley farmland soil exceeded their corresponding reference values. Soils were not contaminated with As, Cr, Mn, and Ni but were slightly contaminated with Co, Cu, Pb, V, and Zn. Their comprehensive pollution levels were moderate to serious. The ecological risk index of single heavy metal(loid) decreased in the sequence As > Pb > Co > Cu > Ni > V > Zn > Cr > Mn. The source analysis results indicated that Cu, Pb, Zn, and As were highly affected by anthropogenic inputs, e.g., metal smelting and agricultural activities, while Mn, Ni, Cr, and V were principally derived from a natural source. As for Co, it was affected by a mixture source of nature, fossil fuel combustion, and fertilizer.