Xml 序列化(备注)

1,去除默认命名空间:

XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
nameSpaces.Add("", "");

2,添加新的命名空间:

XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
nameSpaces.Add("name1", "name1value");

3,去除XML申明、格式化输出:

<?xml version="1.0" encoding="utf-16"?>
XmlWriterSettings xmlSetting = new XmlWriterSettings()
 {
      OmitXmlDeclaration = false,
      Indent = true,
      Encoding = Encoding.UTF8,
};

4,属性申明:

XmlElement 作用在序列上,不会生成序列根节点。

序列化 Demo :

XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
nameSpaces.Add("", "");

XmlWriterSettings xmlSetting = new XmlWriterSettings()
{
    OmitXmlDeclaration = false,
    Indent = true,
    Encoding = Encoding.UTF8,
};

StringBuilder sb = new StringBuilder();

using (XmlWriter xw = XmlWriter.Create(sb, xmlSetting))
{
    XmlSerializer xmlSer = new XmlSerializer(typeof(RssChannelElement));
    xmlSer.Serialize(xw, channel, nameSpaces);
}

return sb.ToString();