将对象序列化为 xml 和字符串,不带 \r\n 特殊字符
我想将我的对象序列化为 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 " 之后的字符串。但我想根本不生成它们,而不是稍后删除它们。
感谢您的宝贵时间。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以尝试:
对我来说,给出:
You could try:
which for me, gives:
我使用了上面的输入,下面是一个可在任何地方重复使用的 XML 字符串方法的通用对象:
I used the input above, and here is a generic object to XML string method to be re-used anywhere: