如何使用C#代码从XML文件生成一个C#类,而不使用Visual Studio GUI或命令行?

huangapple go评论59阅读模式
英文:

How to generate a C# class from an XML file without using Visual Studio GUI or command line but using C# code?

问题

我想将XML文件的内容转换为C#类。我可以使用哪个NuGet包,以及如何使用它们?

我的问题是,我想从已经包含个人信息的XML文件创建一个类(例如Person)类。

XML文件示例:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
    <Id>3344</Id>
    <Name>Ahmed Shaikoun</Name>
    <Title>Software Engineer</Title>
    <Country>Egypt</Country>
    <Phone>0xx-xxxxxxxxx</Phone>
</Person>

从这个XML文件中,我想使用NuGet包中的库来通过代码(而非Visual Studio提示或命令行)生成一个名为Person的C#类。能帮助我吗?谢谢。

英文:

I want to convert the contents of an XML file into a C# class. Which NuGet package can I use, and how can I use them?

My question is that I want to create a class (e.g. Person) class from an XML file that already contains person information.

Example for XML file:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;Person&gt;
    &lt;Id&gt;3344&lt;/Id&gt;
    &lt;Name&gt;Ahmed Shaikoun&lt;/Name&gt;
    &lt;Title&gt;Software Engineer&lt;/Title&gt;
    &lt;Country&gt;Egypt&lt;/Country&gt;
    &lt;Phone&gt;0xx-xxxxxxxxx&lt;/Phone&gt;
&lt;/Person&gt;

From this XML file, I want to generate a C# class with the name of class is Person by code (not Visual Studio tips or command line) using a library from the NuGet package.

Can you help me with this? Thank you.

答案1

得分: 1

你需要使用命名空间 "System.Xml.Serialization" 来使用 XmlSerializer 类,因为它具有你所需的功能,可以将对象序列化和反序列化为 XML 格式,以便对已知类型进行操作,比如你将创建的用户自定义类。

这是一个简单的示例,假设你有一个名为 Person.xml 的 XML 文件,其中包含以下数据:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
    <Id>3344</Id>
    <Name>Ahmed Shaikoun</Name>
    <Title>Software Engineer</Title>
    <Country>Egypt</Country>
    <Phone>0xx-xxxxxxxxx</Phone>
</Person>

你想创建一个控制台应用程序,仅处理该文件,可以加载其中的数据或使用内置的支持 .NET 框架中处理 XML 的功能来向其中写入数据。首先,你需要为这个人定义一个类类型,如下所示:

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }

    public override string ToString()
    {
        return $"{Name}, {Title}, Id: {Id}, from {Country}";
    }
}

然后,你将创建一个新的类,负责序列化/反序列化和解析,当然还要将反序列化的对象加载到内存中:

public class XMLSerializer
{
    public T Deserialize<T>(string input) where T : class
    {
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

        using (StringReader sr = new StringReader(input))
        {
            return (T)ser.Deserialize(sr);
        }
    }

    public string Serialize<T>(T ObjectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

        using (StringWriter textWriter = new StringWriter())
        {
            xmlSerializer.Serialize(textWriter, ObjectToSerialize);
            return textWriter.ToString();
        }
    }
}

非常简单,最后你可以尝试运行我为你创建的这个简单示例:

static void Main(string[] args)
{
    Console.WriteLine("Hello, World!");

    XMLSerializer serializer = new XMLSerializer();

    // load file
    string filePath = Directory.GetCurrentDirectory() + @"\Person.xml";
    string xmlInputData = File.ReadAllText(filePath);
    // deserialize and parse xml to person object
    Person person = serializer.Deserialize<Person>(xmlInputData);
    // display person object
    Console.WriteLine($"Serialize and display person: {person.ToString()}");

    // serialize person object to string content
    string xmlOutputData = serializer.Serialize<Person>(person);
}

这就是你所需要的,无需手动处理数据,也不需要构建任何 GUI。

下面是我为你准备的完整示例:

namespace XMLSerialize
{
    internal class Program
    {
        // ...(与原文相同)
    }

    // ...(与原文相同)
}

XmlSerializer 定义在 System.Xml.XmlSerializer 程序集中,它也适用于 .NET 7。

希望我的回答能帮助你完成这个任务。谢谢。

英文:

I think you will need namespace "System.Xml.Serialization" to use class XmlSerializer because it has the functionality that you want that will serialize and deserialize to/from XML format to object against known type, like user defined class you will create.

Here is a quick example for you, suppose you have xml file named Person.xml and it is contains these data:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;Person&gt;
    &lt;Id&gt;3344&lt;/Id&gt;
    &lt;Name&gt;Ahmed Shaikoun&lt;/Name&gt;
    &lt;Title&gt;Software Engineer&lt;/Title&gt;
    &lt;Country&gt;Egypt&lt;/Country&gt;
    &lt;Phone&gt;0xx-xxxxxxxxx&lt;/Phone&gt;
&lt;/Person&gt;

And you would like to create console application to just deal with this file to load data from it or to write data to it using built in functionality that support dealing with xml inside .NET framework, all you need first to define class type for this person like this:

 public class Person
    {
        public string Id { get; set;}
        public string Name { get; set;}
        public string Title { get; set;}
        public string Country { get; set;}
        public string Phone { get; set;}

        public override string ToString()
        {
            return $&quot;{Name}, {Title}, Id: {Id}, from {Country}&quot;;
        }

    }

Then you will create a new class that will do the serialization/deserialization and parsing of course to load the deserialized object to memory:

public class XMLSerializer
    {
        public T Deserialize&lt;T&gt;(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }

        public string Serialize&lt;T&gt;(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                return textWriter.ToString();
            }
        }
    }

It is pretty easy, and last you can try it by running this easy example that i made here for you:

 static void Main(string[] args)
        {
            Console.WriteLine(&quot;Hello, World!&quot;);


            XMLSerializer serializer = new XMLSerializer();

            // load file
            string filePath = Directory.GetCurrentDirectory() + @&quot;\Person.xml&quot;;
            string xmlInputData = File.ReadAllText(filePath);
            // deserialize and parse xml to person object
            Person person = serializer.Deserialize&lt;Person&gt;(xmlInputData);
            // display person object
            Console.WriteLine($&quot;Serialize and display person: {person.ToString()}&quot;);

            // serialize person object to string content
            string xmlOutputData = serializer.Serialize&lt;Person&gt;(person);
        }
    }

This is all you need without dealing manually with data and also it did not require any GUI to build.

And here the full example that I prepared here:

namespace XMLSerialize
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(&quot;Hello, World!&quot;);


            XMLSerializer serializer = new XMLSerializer();

            // load file
            string filePath = Directory.GetCurrentDirectory() + @&quot;\Person.xml&quot;;
            string xmlInputData = File.ReadAllText(filePath);
            // deserialize and parse xml to person object
            Person person = serializer.Deserialize&lt;Person&gt;(xmlInputData);
            // display person object
            Console.WriteLine($&quot;Serialize and display person: {person.ToString()}&quot;);

            // serialize person object to string content
            string xmlOutputData = serializer.Serialize&lt;Person&gt;(person);
        }
    }

    public class Person
    {
        public string Id { get; set;}
        public string Name { get; set;}
        public string Title { get; set;}
        public string Country { get; set;}
        public string Phone { get; set;}

        public override string ToString()
        {
            return $&quot;{Name}, {Title}, Id: {Id}, from {Country}&quot;;
        }

    }
    public class XMLSerializer
    {
        public T Deserialize&lt;T&gt;(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }

        public string Serialize&lt;T&gt;(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                return textWriter.ToString();
            }
        }
    }
}

XmlSerializer is defined in Assembly System.Xml.XmlSerializer, it is working with .NET 7 too.

I hope my little answer helping you to do this task.
Thank you

huangapple
  • 本文由 发表于 2023年2月19日 23:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定