How to convert XML/JSON file to C# class?

前端 未结 4 1016
不知归路
不知归路 2020-12-02 23:59

I have XML file like this:



    

        
相关标签:
4条回答
  • 2020-12-03 00:26

    You have two possibilities.

    Method 1. XSD tool


    Suppose that you have your XML file in this location C:\path\to\xml\file.xml

    1. Open Developer Command Prompt
      You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
    2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
    3. Create XSD file from your xml file by typing xsd file.xml
    4. Create C# classes by typing xsd /c file.xsd

    And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

    Method 2 - Paste special


    Required Visual Studio 2012+

    1. Copy content of your XML file to clipboard
    2. Add to your solution new, empty class file (Shift+Alt+C)
    3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
      enter image description here

    And that's it!

    Usage


    Usage is very simple with this helper class:

    using System;
    using System.IO;
    using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace Helpers
    {
        internal static class ParseHelpers
        {
            private static JavaScriptSerializer json;
            private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }
    
            public static Stream ToStream(this string @this)
            {
                var stream = new MemoryStream();
                var writer = new StreamWriter(stream);
                writer.Write(@this);
                writer.Flush();
                stream.Position = 0;
                return stream;
            }
    
    
            public static T ParseXML<T>(this string @this) where T : class
            {
                var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
                return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
            }
    
            public static T ParseJSON<T>(this string @this) where T : class
            {
                return JSON.Deserialize<T>(@this.Trim());
            }
        }
    }
    

    All you have to do now, is:

        public class JSONRoot
        {
            public catalog catalog { get; set; }
        }
        // ...
    
        string xml = File.ReadAllText(@"C:\path\to\xml\file.xml");
        var catalog1 = xml.ParseXML<catalog>();
    
        string json = File.ReadAllText(@"C:\path\to\json\file.json");
        var catalog2 = json.ParseJSON<JSONRoot>();
    

    Here you have some Online XML <--> JSON Converters: Click

    0 讨论(0)
  • 2020-12-03 00:29

    You can follow this simple step

    1.Please Add using System.Xml as a reference;
    2.Make a class named book in this way
    
    
    
         public class book
                {
                    public Nullable<System.DateTime> date{ get; set; }
                    public decimal price { get; set; }
                    public string title { get; set; }
                    public string description { get; set; }
            }
    
        try
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load("Write down full path");
                        XmlNodeList dataNodes = xmlDoc.SelectNodes("/catalog");
    
                        foreach (XmlNode node in dataNodes)
                        {
                            book objbook = new book();
                         objbook.date=Convert.ToDateTime(node.Attributes["date"].Value);
                           objbook.title=node.SelectSingleNode("title").InnerText;
                       objbook.description=node.SelectSingleNode("description").InnerText;
    objbook.price=Convert.ToDecimal(node.SelectSingleNode("price").InnerText);
    
                        }
    
                    }
    catch(Exception ex)
    {
    throw ex;
    }
    
    0 讨论(0)
  • 2020-12-03 00:32

    Use the super simple way using 'Paste XML As Classes' functionality in Visual studio menu.

    1.copy the xml source in the clipboard, something like CTRL+A and CTRL+C

    2.Go to 'Edit' Menu -> Paste Special -> Paste XML As Classes, to paste the generated classes based on the source xml"

    Ref: More steps in detail at this link

    0 讨论(0)
  • 2020-12-03 00:49

    Use the XML Schema Definition Tool xsd.exe found in your framework tools to convert your schema into a serializable class or dataset.

    xsd file.xsd {/classes | /dataset} [/element:element]
             [/language:language] [/namespace:namespace]
             [/outputdir:directory] [URI:uri]
    

    And in example, whereas the C# class will be generated in the same directory as the xsd tool:

    xsd /c YourFile.xsd
    
    0 讨论(0)
提交回复
热议问题