[quoted text, click to view] dheeraj dhondalkar via .NET 247 wrote:
[quoted text, click to view] > 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?
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/