zoukankan      html  css  js  c++  java
  • (转)使用VS实现XML2CS

    转自 StackOverFlow

    Method 1 XSD tool

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

    • 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
    • Change location to your XML file directory by typing cd /D "C:path oxml"
    • Create XSD file from your xml file by typing xsd file.xml
    • Create C# classes by typing xsd /c file.xsd
      And that's it! You have generated C# classes from xml file in C:path oxmlfile.cs

    Method 2 Paste special

    • Copy content of your XML file to clipboard
    • Add to your solution new, empty class file (Shift+Alt+C)
    • Open that file and in menu click Edit > Paste special > Paste XML As Classes
      XMLTOCS1

    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(@"D:file.xml");
        var catalog1 = xml.ParseXML<catalog>();
    
        string json = File.ReadAllText(@"D:file.json");
        var catalog2 = json.ParseJSON<JSONRoot>();
    
  • 相关阅读:
    Lab BGP RTBH
    Lab BGP ORF
    Lab BGP Maximum-Prefix
    Lab BGP 路由翻动(route flaps)
    Lab BGP Peer-Group
    Lab BGP Dampening
    BGP Dampening Cyrus
    BGP进程工作步骤
    5、为什么域名解析用UDP协议?6、为什么区域传送用TCP协议?
    3、你知道DNS是什么?4、DNS的工作原理?
  • 原文地址:https://www.cnblogs.com/FounderBox/p/4656244.html
Copyright © 2011-2022 走看看