You are correct in stating that there are plenty of ways to protect your application from attacks such as XSS and SQLi. Unfortunately there are many reasons why these types of attacks are still the most popular type of attack. Consider the following possible reasons security is not always driven in a project:
Legacy code - There are plenty of applications that have been created years ago before security considerations became slightly more popular. These applications typically do not have a lot of ongoing development but are still available online
Developers / Engineers - The focus of these typically smart people are to create applications that address a business need. If the individual is not aware of the types of attacks that can happen, they simply won't prepare for it since their focus is getting the application built and deployed. If you never thought of the fact that the user might not be trusted, how could you possibly defend against it?
Time constraints - Business budgets rarely allocate sufficient time for security testing since it is relatively expensive and as any developer can tell you. There is almost always scope creep that eats into the testing budget
Rapid change in technology frameworks - Many developers / engineers are required to assimilate new technology rather quickly. Getting enough information to create the project does not always leave enough time to gain a proper understanding of the security options available in the framework
These are but a few possible reasons. My personal feeling is that developing secure applications at present requires at least some form of additional interest from developers / engineers / architects. The fundamentals are only slowly making its way into most university and other training institutions curriculums.
EDIT: Worked on my mobile at first and did not see the duplicate comments. Your question has definitly been addressed much better here: SQL injection is 17 years old. Why is it still around?