Groups | Blog | Home
all groups > dotnet xml > august 2004 >

dotnet xml : How to suppress XML serialzation generateed the comment line?



dheeraj dhondalkar via .NET 247
8/6/2004 6:25:16 PM
(Type your message here)
Hi,

static string SerializeThingToXmlString(object thing)
{
StringWriter stringWriter = new StringWriter();
XmlSerializer serializer = new XmlSerializer(thing.GetType());
serializer.Serialize(stringWriter, thing);
return stringWriter.ToString();
}

This returns a string which contains the first line <?xml version="1.0" encoding="utf-8"?>
How can I suppress this line? Surely I can substring, but thats lot of effort. I have used it heavily and may need to change at so many place. Any other way?
Thanks in advance
Dheeraj

--------------------------------
From: dheeraj dhondalkar

-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)

Martin Honnen
8/7/2004 2:11:30 PM


[quoted text, click to view]


[quoted text, click to view]

It would probably better to ask you why you do not want the XML
declaration as it usually does no harm at all but in the following
example XmlTextWriter is extended to provide a version that doesn't
write an XML declaration by overriding the method WriteStartDocument to
do nothing.

using System;

using System.Xml;

using System.Xml.Serialization;

public class XmlTextWriterNoDeclaration : XmlTextWriter {
public XmlTextWriterNoDeclaration (System.IO.TextWriter w) : base(w) { }
public override void WriteStartDocument () { }
}

public class Test2004080701 {

public class Person {
private string _name;

public string Name {
get {
return _name;
}
set {
_name = value;
}
}
}

public static void Main (string[] args) {
Person p1 = new Person();
p1.Name = "Kibo";

Console.WriteLine("p1 serialized is: {0}.",
SerializeThingToXmlString(p1));
}

static string SerializeThingToXmlString(object thing) {
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
XmlWriter xmlWriter = new XmlTextWriterNoDeclaration(stringWriter);
XmlSerializer serializer = new XmlSerializer(thing.GetType());
serializer.Serialize(xmlWriter, thing);
return stringWriter.ToString();
}

}


The example output then is

p1 serialized is: <Person xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Name>Kibo</Name></Person>.

so there is no XML declaration.



--

Martin Honnen
http://JavaScript.FAQTs.com/
AddThis Social Bookmark Button