2010-10-25 7 views
13

Je souhaite sérialiser mon objet en xml puis en une chaîne.Sérialisation de l'objet en xml et chaîne sans caractères spéciaux

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

Je veux obtenir une chaîne de ligne unique qui lok comme ceci:

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

J'utilise ce 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(); 

C'est le plus proche de ce que je reçois :

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

Je sais que je pourrais enlever "\ r \ n" de la chaîne après. Mais je ne voudrais pas les produire du tout plutôt que de les supprimer plus tard.

Merci pour votre temps.

Répondre

12

Vous pouvez essayer:

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

qui, pour moi, donne:

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

Merci Mark, ça marche. Merci pour la correction dans le sujet aussi. – Wodzu

7

je l'entrée ci-dessus, et est un objet générique ici à la méthode de chaîne XML pour être réutilisés partout :

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

Exactement ce dont j'avais besoin. Je vous remercie! –

+0

Merci! Il peut être fait la méthode d'extension aussi. –

Questions connexes