enter image description here

When writing an object in xml, I get the following (see screen). How to make the record that follows the report tag and not before the eeprom tag. And how to add the following to the beginning of the file

<?xml version="1.0" encoding="ISO8859-1"?> 

    2 answers 2

    Try this:

     XmlSerializer s = new XmlSerializer(objectToSerialize.GetType()); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("",""); s.Serialize(xmlWriter, objectToSerialize, ns); 

    enSO

      To define serialization settings, use the XmlWriterSetting class, which has parameters

      • OmitXmlDeclaration - returns or sets a value that determines whether to omit the XML declaration.
      • Encoding - Gets or sets the type of text encoding used.

      Then your code will look like this.

       XmlSerializer formatter = new XmlSerializer(typeof(Report)); // объект, который сериализуем Report obj = new Report(); // опускаем все определения пространств имен XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("",""); //получаем поток, куда будем записывать сериализованный объект using (FileStream fs = new FileStream(pathXmlFileWrite, FileMode.OpenOrCreate)) { XmlWriter writer = XmlWriter.Create(fs, new XmlWriterSettings() { OmitXmlDeclaration = false, Indent = true, Encoding = Encoding.GetEncoding("ISO-8859-1") }); formatter.Serialize(writer, obj, ns); } 

      In the serialization settings, we explicitly specified not to delete the XmlDeclaration and set the Latin1 (ISO8859-1) encoding via the Encoding property.

      • All the same, what is after report (in red) is written in xml - SVD102
      • @ SVD102, everything written after the report should be removed using the answer above. My answer is the answer to the question of how to set the encoding in the xml definition. I did not duplicate the answer above. Have you tried your code with the combination of these answers? - Alexcei Shmakov
      • @ SVD102, edited the answer. Added lowering all namespaces when serializing an object. - Alexcei Shmakov
      • I can not understand how to combine your code and which is higher. - SVD102
      • @ SVD102, I have already combined it, try it - Alexcei Shmakov