0

I have the following class:

[XmlType("supervisor")]
public class Supervisor
{
   [XmlAttribute("id")]
    public string Id { set; get; }

    [XmlElement("Name")]
    public string Name { set; get; }

    [XmlElement("Contract")]
    public int Contracts { set; get; }

    [XmlElement("Volume")]
    public long Volume { set; get; }

    [XmlElement("Average")]
    public int Average { set; get; }
}

which reads from XML file:

 <digital-sales xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <supervisor id="1236674">
        <Name>Hiroki</Name>
        <Contract>11</Contract>
        <Volume>1036253</Volume>
        <Average>94205</Average>
    </supervisor>
    <supervisor id="123459">
        <Name>Ayumi</Name>
        <Contract>5</Contract>
        <Volume>626038</Volume>
        <Average>125208</Average>
    </supervisor> ...
 </digital-sales>

in the code I create List and process it. now I want to write the List to XML file while maintaining the same XML structure. How do I do that?

How to use xml id to fill class object?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Coder
  • 121
  • 9
  • You cannot have an array at the root level of xml (it is considered Note Well Formed). Simply serializing the digital-sales class will automatically create the same structure that you deserialized. – jdweng Jan 23 '19 at 18:07
  • Can you share an example please . Am not familiar with the syntax – Coder Jan 23 '19 at 18:10

1 Answers1

2

Here is the code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;


namespace ConsoleApplication98
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(DigitalSales));
            DigitalSales digitalSales = (DigitalSales)serializer.Deserialize(reader);

            reader.Close();

            XmlWriter writer = XmlWriter.Create(FILENAME);
            serializer.Serialize(writer, digitalSales);

        }
    }


    [XmlRoot("digital-sales")]
    public class DigitalSales
    {
        [XmlElement("supervisor")]
        public List<Supervisor> supervisor { get; set; }

    }
    [XmlRoot("supervisor")]
    public class Supervisor
    {
        [XmlAttribute("id")]
        public string Id { set; get; }

        [XmlElement("Name")]
        public string Name { set; get; }

        [XmlElement("Contract")]
        public int Contracts { set; get; }

        [XmlElement("Volume")]
        public long Volume { set; get; }

        [XmlElement("Average")]
        public int Average { set; get; }
    }


}
jdweng
  • 33,250
  • 2
  • 15
  • 20