D
D
Daniil Grishchenko2021-07-18 17:10:07
C++ / C#
Daniil Grishchenko, 2021-07-18 17:10:07

How to properly deserialize XML in C#?

Please help me, I am learning to work with XML format in c#. There were problems deserializing the file. With direct deserialization, an error is displayed (screen below 60f435cacb778089398362.png)
code:

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Test
{
    public class obj
    {
        string ProjectName;
        string MemberRole;
        string MemberName;

        public obj()
        {

        }
    }
    public class XmlToXml
    {
        public string path;
        public XmlDocument CurDoc = new XmlDocument();
        public XmlNode DocRoot;
        public void PutIn(string path)
        {
            this.path = path;
            CurDoc.Load(path);
            DocRoot = CurDoc.DocumentElement;
        }
        public void Deserialization()
        {
            XmlSerializer Deserializator = new XmlSerializer(typeof(obj[]));
             using (FileStream origin = new FileStream(path, FileMode.Open))
             {
                 obj[] ObjArray = (obj[])Deserializator.Deserialize(origin);
             }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            XmlToXml a = new XmlToXml();
            a.PutIn(@"C:\Users\Даниил\source\repos\4-Задачи\TaskFromTheInterviewXml1.0Tests\TestXmlL1.xml");
            a.Deserialization();
        }
    }
}


Xml File:
<projects>
    <project name="xml">
        <member role="developer" name="Fedya"/>
  <member role="manager" name="Ivan"/>
  <member role="manager" name="Fedya"/>
    </project>
</projects>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2021-07-18
@Mayver516

It’s better to start with taking your object and serializing it to xml and comparing it with what is published ...
Well, or “lazy” ask VS to generate classes from xml ( Edit -> PasteSpecial) and then compare it with your class

G
Griboks, 2021-07-18
@Griboks

I want to add that such deserialization is not recommended in principle, because it allows the injection of malicious code into your program. It is recommended to parse the file and construct the object accordingly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question