2010-10-25 6 views
13

Desidero serializzare il mio oggetto su xml e quindi su una stringa.Serializzazione dell'oggetto su xml e stringa senza caratteri speciali r n

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

voglio ottenere un stringa singola linea che lok come questo:

<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 potrei rimuovere "\ r \ n" dalla stringa in seguito. Ma mi piacerebbe non produrli affatto piuttosto che rimuoverli in seguito.

Grazie per il vostro tempo.

risposta

12

Si potrebbe provare:

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

che per me, dà:

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

Grazie Mark, funziona. Grazie per la correzione anche nell'argomento. – Wodzu

7

ho usato l'input di cui sopra, e qui è un oggetto generico metodo stringa XML per essere ri-utilizzato 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; 
} 
+0

Esattamente quello di cui avevo bisogno. Grazie! –

+0

Grazie! Può anche essere reso un metodo di estensione. –

Problemi correlati