gpt4 book ai didi

c# - 将对象序列化为不带\r\n 特殊字符的 xml 和字符串

转载 作者:可可西里 更新时间:2023-11-01 07:54:54 25 4
gpt4 key购买 nike

我想将我的对象序列化为 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”。但我想完全不生产它们,而不是稍后删除它们。

感谢您的宝贵时间。

最佳答案

你可以试试:

settings.NewLineHandling = NewLineHandling.None;
settings.Indent = false;

对我来说,给出:

<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>

关于c# - 将对象序列化为不带\r\n 特殊字符的 xml 和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com