我想将我的对象序列化为 xml,然后再序列化为字符串。
public class MyObject
{
[XmlElement]
public string Name
[XmlElement]
public string Location;
}
我想获得一个像这样的单行字符串:
<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>
我正在使用这样的代码:
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();
这是我得到的最接近的:
<MyObject>\r\n <Name>Vladimir</Name>\r\n <Location>Moskov</Location>\r\n</MyObject>
我确实知道之后我可以从字符串中删除“\r\n”。但我想根本不生产它们,而不是以后删除它们。
谢谢你的时间。