Domanda

Voglio serializzare il mio oggetto in XML e poi in una stringa.

  public class MyObject
  {
    [XmlElement]
    public string Name
    [XmlElement]
    public string Location;
  }

Voglio ottenere un singola riga stringa che lok in questo modo:

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

Sto usando questo codice:

  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();

Questo è il più vicino che cosa ottengo:

<MyObject>\r\n  <Name>Vladimir</Name>\r\n  <Location>Moskov</Location>\r\n</MyObject>

So che avrei potuto rimuovere "\ r \ n" dalla stringa dopo. Ma vorrei non producono affatto, piuttosto che rimuoverli in seguito.

Grazie per il vostro tempo.

È stato utile?

Soluzione

Si potrebbe provare:

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

che per me, dà:

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

Altri suggerimenti

ho usato l'input di cui sopra, ed ecco un oggetto generico metodo stringa XML per essere riutilizzati ovunque:

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top