代码之家  ›  专栏  ›  技术社区  ›  Wodzu

将对象序列化为不带特殊字符的xml和字符串

  •  14
  • Wodzu  · 技术社区  · 14 年前

    我想将对象序列化为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”。但我不想再生产它们,而不愿以后再把它们移走。

    谢谢你的时间。

    2 回复  |  直到 14 年前
        1
  •  14
  •   Marc Gravell    14 年前

    你可以试试:

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

    对我来说,是:

    <MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>
    
        2
  •  8
  •   Aristos    8 年前

    我使用了上面的输入,这里有一个通用的object-to-XML字符串方法,可以在任何地方重用:

    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;
    }