Remove useless condition and use local document instead of global document.
Use XMLSerilalizer for xml serialization.
Use local document instead of global document.
Use local document instead of global document and make additional checks for localName.