1. 去掉 attribute 里面的 xmlns:xsi 和 xmlns:xsd
output:
<?xml version="1.0" encoding="utf-16"?><Class1 property="My property" />
如果运行第9行,output则是:
<?xml version="1.0" encoding="utf-16"?><Class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" property="My property" />
关键在与:在Serialize对象时,传入一个XmlSerializerNamespaces,这样XmlSerializer就会用你传入的XmlSerializerNamespaces而不会用default的XmlSerializerNamespaces。
2. 删除XmlDeclaration:<?xml version="1.0" encoding="utf-16"?>
其实很简单,只有在创建XmlWriter的时候传入一个XmlWriterSettings就可以了,具体见代码第8-10行:
output:
<Class1 property="My property" />
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(Class1));
- Class1 class1 = new Class1();
- class1.Property = "My property";
- StringBuilder stringBuilder = new StringBuilder();
- XmlSerializerNamespaces xmlSerializerNamespaces=new XmlSerializerNamespaces();
- xmlSerializerNamespaces.Add("","");
- using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
- {
- //xmlSerializer.Serialize(xmlWriter, class1);
- xmlSerializer.Serialize(xmlWriter, class1, xmlSerializerNamespaces);
- System.Diagnostics.Debug.WriteLine(stringBuilder.ToString());
- }
<?xml version="1.0" encoding="utf-16"?><Class1 property="My property" />
如果运行第9行,output则是:
<?xml version="1.0" encoding="utf-16"?><Class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" property="My property" />
关键在与:在Serialize对象时,传入一个XmlSerializerNamespaces,这样XmlSerializer就会用你传入的XmlSerializerNamespaces而不会用default的XmlSerializerNamespaces。
2. 删除XmlDeclaration:<?xml version="1.0" encoding="utf-16"?>
其实很简单,只有在创建XmlWriter的时候传入一个XmlWriterSettings就可以了,具体见代码第8-10行:
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(Class1));
- Class1 class1 = new Class1();
- class1.Property = "My property";
- StringBuilder stringBuilder = new StringBuilder();
- XmlSerializerNamespaces xmlSerializerNamespaces=new XmlSerializerNamespaces();
- xmlSerializerNamespaces.Add("","");
- XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
- xmlWriterSettings.OmitXmlDeclaration = true;
- using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
- {
- xmlSerializer.Serialize(xmlWriter, class1, xmlSerializerNamespaces);
- System.Diagnostics.Debug.WriteLine(stringBuilder.ToString());
- }
<Class1 property="My property" />