//準備序化列對象
XmlSerializer xs = new XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
//設置序序化XML格式
XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8;
XmlWriter xtw = XmlTextWriter.Create(ms, xws);
//去掉要結點的 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 屬性
XmlSerializerNamespaces _namespaces = new XmlSerializerNamespaces(
new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "aa")
});
xs.Serialize(xtw, obj,_namespaces);
ms.Position = 0;
xmlDoc = new XmlDocument();
xmlDoc.Load(ms);
//給文檔添加<?xml version="1.0" encoding="utf-8"?>
XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.InsertBefore(xmlDecl, xmlDoc.DocumentElement);