XML Serialization with .NET
I'm tryng to serialize an object to XML by using C# with the following code:
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memo开发者_开发知识库ryStream);
return streamReader.ReadToEnd();
My problem is that this produce the following output in the part of the document:
<?xml version="1.0"?>
And I want to have the following:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
Does anybody know how to include both the "encoding" and "standalone" attribute?
I saw this, but it seems that is not producing the output I need.
Thanks!
Try following
MyClass instance = new MyClass ();
// fill instance
XmlSerializer serializer = new XmlSerializer (typeof (MyClass));
XmlWriterSettings settings = new XmlWriterSettings ();
settings.OmitXmlDeclaration = true;
settings.Encoding = Encoding.UTF8;
// next two settings are optional
settings.Indent = true;
settings.IndentChars = " ";
using (XmlWriter writer = XmlWriter.Create ("test.xml", settings)) {
writer.WriteRaw ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n");
serializer.Serialize (writer, instance);
}
UPDATED: By the way if you don't want to have
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
as attribute of the root elements in the XML file and have no namespaces at all you produce you can use [XmlRoot(Namespace="")]
as atribute of your calss MyClass
and replace line
serializer.Serialize (writer, instance);
with the lines
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces ();
namespaces.Add (string.Empty, string.Empty);
serializer.Serialize (writer, instance, namespaces);
Is this tagged as serializable? If yes do you have the properties you want public? Maybe you should also post your source of (this)
Here is a good starting point: LINK
精彩评论