Microsoft recommend to use XmlWriter instead of XmlTextWriter
https://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter(v=vs.110).aspx
public string Serialize(BackgroundJobInfo info)
{
var stringBuilder = new StringBuilder();
using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
{
var writer = new XmlTextWriter(stringWriter);
new DataContractSerializer(typeof(BackgroundJobInfo)).WriteObject(writer, info);
}
return stringBuilder.ToString();
}
How to correctly use XmlWriter in my method instead of XmlTextWriter?
I'd use the factory method Create on XmlWriter class like:
var stringBuilder = new StringBuilder();
using(var writer = XmlWriter.Create(stringBuilder))
{
new DataContractSerializer(typeof(BackgroundJobInfo)).WriteObject(writer, info)
}
Or you can do it without XmlWriter
public static string Serialize(BackgroundJobInfo info)
{
string result = String.Empty;
using (var ms = new MemoryStream())
{
var sw = new StreamWriter(ms);
DataContractSerializer dcs = new DataContractSerializer(typeof(BackgroundJobInfo));
dcs.WriteObject(ms, info);
sw.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
result = sr.ReadToEnd();
}
return result;
}
Related
Using the below code, I can serialize / deserialize PrinterSettings to a file.
I would like to ask if there's a way to serialize it to a string or byte array or similar instead in order to save it directly into a database.
Thank you!
PrinterSettings prtSettings = new PrinterSettings();
prtSettings.PrintFileName = "does not matter, unused if PrintToFile == false";
//serialise
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(prtSettings.GetType());
using (System.IO.TextWriter txtWriter = new StreamWriter(#"c:\temp\printerSettings.xml"))
{
xmlSerializer.Serialize(txtWriter,prtSettings);
}
//deserialise
using (FileStream fileStream = new FileStream(#"c:\temp\printerSettings.xml", FileMode.Open))
{
object obj = xmlSerializer.Deserialize(fileStream);
prtSettings = (PrinterSettings)obj;
}
Instead of a StreamWriter use a StringWriter
string printerSettingText = "";
XmlSerializer xser = new XmlSerializer(typeof(PrinterSettings));
using (StringWriter sw = new StringWriter())
{
xser.Serialize(sw, prtSettings);
printerSettingText = sw.ToString();
}
Deserialization of the object is simple like this
string dataToDeserialize = GetYourDataFromDb();
xser = new XmlSerializer(typeof(PrinterSettings));
using (StringReader sr = new StringReader(dataToDeserialize))
{
PrinterSettings prn = (PrinterSettings)xser.Deserialize(sr);
Console.WriteLine(prn.PrintFileName);
}
I am trying to get the raw string of the RSS xml. I tried the below but my string builder ends up blank. What is the correct way to do this?
var rssFormatter = new Rss20FeedFormatter(feed, false);
var output = new StringBuilder();
using (var writer = XmlWriter.Create(output, new XmlWriterSettings { Indent = true }))
{
rssFormatter.WriteTo(writer);
return output;
}
You probably want to flush your writer...
var rssFormatter = new Rss20FeedFormatter(feed, false);
var output = new StringBuilder();
using (var writer = XmlWriter.Create(output, new XmlWriterSettings { Indent = true }))
{
rssFormatter.WriteTo(writer);
writer.Flush();
return output;
}
I had a quick question regarding the datacontractserializer. Maybe it's more of a stream question. I found a piece of code that writes the xml to a filestream. I basically don't want the file and just need the string output.
public static string DataContractSerializeObject<T>(T objectToSerialize)
{
var fs = new FileStream("test.xml", FileMode.OpenOrCreate);
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fs, objectToSerialize);
fs.Close();
return fs.ToString();
}
fs.ToString() is obviously not what I'm looking for. What stream or writer etc, can I use just to return the proper string and not create a file? I did look at the XML the filestream created and it's exactly what I'm looking for. The XmlSerializer wrote the XML a bit strange and I prefer the output of the DataContractSerializer in this case. Can anyone point me in the right direction?
Something like this - put your output into a MemoryStream and then read that back in:
public static string DataContractSerializeObject<T>(T objectToSerialize)
{
using(MemoryStream memStm = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memStm, objectToSerialize);
memStm.Seek(0, SeekOrigin.Begin);
using(var streamReader = new StreamReader(memStm))
{
string result = streamReader.ReadToEnd();
return result;
}
}
}
Thanks to #xr280xr for pointing out my forgotten StringWriter disposal in the first draft.
/// <summary>
/// Converts this instance to XML.
/// </summary>
/// <returns>XML representing this instance.</returns>
public string ToXml()
{
var serializer = new DataContractSerializer(this.GetType());
using (var output = new StringWriter())
using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
{
serializer.WriteObject(writer, this);
return output.GetStringBuilder().ToString();
}
}
And even easier:
var serializer = new DataContractSerializer(typeof(T));
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb))
{
serializer.WriteObject(writer, objectToSerialize);
writer.Flush();
return sb.ToString();
}
I suggest combining the methods given by Pat and marc_s:
public static string DataContractSerializeObject<T>(T objectToSerialize)
{
using (var output = new StringWriter())
using (var writer = new XmlTextWriter(output) {Formatting = Formatting.Indented})
{
new DataContractSerializer(typeof (T)).WriteObject(writer, objectToSerialize);
return output.GetStringBuilder().ToString();
}
}
A variant of #root's answer:
var serializer = new DataContractSerializer(typeof(T));
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb))
{
serializer.WriteObject(writer, objectToSerialize);
}
return sb.ToString();
I am writing common functions to serialize the given object and List<object> as follows
public string SerializeObject(Object pObject)// for given object
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
public string SerializeObject(List<Object> pObject)// for given List<object>
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
first one is working fine. If I pass any type, it is successfully returning xml string.
CORRECTION: Compilation error has occurred for second one (Error: cannot convert from List<MyType> to List<object>.
I rewrite the second one as follows which solves my problem. Now it is serializing the given List<generic types>.
private string SerializeObject<T>(T source)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, source);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
string XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
https://weblogs.asp.net/rajbk/Contents/Item/Display/345
The relevant code from the article:
private static string SerializeObject<T>(T source)
{
var serializer = new XmlSerializer(typeof(T));
using (var sw = new System.IO.StringWriter())
using (var writer = XmlWriter.Create(sw))
{
serializer.Serialize(writer, source);
return sw.ToString();
}
}
I have tried your two functions without much trouble. The only thing I changed was this line:
XmlSerializer xs = new XmlSerializer(typeof(pObject));
to this:
XmlSerializer xs = new XmlSerializer(pObject.GetType());
typeof() requires an actual type whereas GetType() returns the type of the object.
I encountered a problem with SOAP serialization and it would be great to find an answer. Here's a very simplified example:
public void Test()
{
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(A));
XmlSerializer serializer = new XmlSerializer(map);
serializer.Serialize(writer, new A());
}
[Serializable]
public class A
{
public A()
{
BB = new B();
}
public int a;
public B BB;
}
[Serializable]
public class B
{
public int A1 { get; set; }
public int A2 { get; set; }
}
If I run method Test() then I get the following exception: System.InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.
Would appreciate any help.
Use XmlWriter instead of StringWriter and do a writer.WriteStartElement("root");
This will work:
Stream s = new MemoryStream();
XmlWriter writer = new XmlTextWriter(s, Encoding.UTF8);
SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(A));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("root");
serializer.Serialize(writer, new A());
StreamReader sr = new StreamReader(s);
string data = sr.ReadToEnd();
Just a note,
The upper example will not work if the position of the stream is not set to the start of the stream. Like so:
Stream s = new MemoryStream();
XmlWriter writer = new XmlTextWriter(s, Encoding.UTF8);
SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(A));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("root");
serializer.Serialize(writer, new A());
s.Position = 0;
StreamReader sr = new StreamReader(s);
string data = sr.ReadToEnd();