Reputation: 6979
I want to serialize my object to xml and then to a string.
public class MyObject
{
[XmlElement]
public string Name
[XmlElement]
public string Location;
}
I want to obtain a single line string which will lok like this:
<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>
I am using such code:
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
StringWriter StringWriter = new StringWriter();
StringWriter.NewLine = ""; //tried to change it but without effect
XmlWriter writer = XmlWriter.Create(StringWriter, settings);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlSerializer MySerializer= new XmlSerializer(typeof(MyObject ));
MyObject myObject = new MyObject { Name = "Vladimir", Location = "Moskov" };
MySerializer.Serialize(writer, myObject, namespaces);
string s = StringWriter.ToString();
This is the closest what I get:
<MyObject>\r\n <Name>Vladimir</Name>\r\n <Location>Moskov</Location>\r\n</MyObject>
I do know that I could remove "\r\n" from the string afterwards. But I would like to not produce them at all rather than removing them later.
Thanks for your time.
Upvotes: 17
Views: 19461
Reputation: 1042
I used the input above, and here is a generic object to XML string method to be re-used anywhere:
public static string ObjectToXmlString(object _object)
{
string xmlStr = string.Empty;
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.OmitXmlDeclaration = true;
settings.NewLineChars = string.Empty;
settings.NewLineHandling = NewLineHandling.None;
using (StringWriter stringWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(_object.GetType());
serializer.Serialize(xmlWriter, _object, namespaces);
xmlStr = stringWriter.ToString();
xmlWriter.Close();
}
stringWriter.Close();
}
return xmlStr;
}
Upvotes: 10
Reputation: 1062530
You could try:
settings.NewLineHandling = NewLineHandling.None;
settings.Indent = false;
which for me, gives:
<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>
Upvotes: 15