Here the
XmlTextWriterFormattedNoDeclaration class definition:
public class XmlTextWriterFormattedNoDeclaration : System.Xml.XmlTextWriter
{
public XmlTextWriterFormattedNoDeclaration(System.IO.TextWriter w) : base(w)
{
//Formatting = System.Xml.Formatting.Indented;
}
public override void WriteStartDocument()
{
// suppress
}
}
And here, how we can use it:
// Create an instance for namespace class
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
// now, serialize the object
XmlSerializer xmlr = new XmlSerializer(typeof(Docs));
StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriterFormattedNoDeclaration(sw);
xmlr.Serialize(tw, docs, ns);
MessageBox.Show(sw.ToString());
For deserialization we have:
// Deserializing the object
StringReader sr = new StringReader(sw.ToString());
Docs docs2 = (Docs) xmlr.Deserialize(sr);
MessageBox.Show(docs2.ToString());
2 comments:
Hi,
Thanks for posting this up. I have some issues with the method. My XML is never written completely with this method. It ends at a child node and does not display in the IE.
I get an error saying that the XML is not valid xml and there is an unclosed tag. I have tried other methods also where I am not getting the result expected but the XML does not have any issues.
I am not sure if I am missing something over here.
Thanks for the help.
I have tested the code, It works well. You must be sure of serializaing only one object at time.
Can you publish a sample of the output you get or some piece of code you are using?
Post a Comment