加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

convert-xml-to-csharp-classes/

发布时间:2020-12-16 02:00:37 所属栏目:百科 来源:网络整理
导读:refs: https://dennymichael.net/2014/05/30/convert-xml-to-csharp-classes/comment-page-1/ Today I foundacool Visual Studio 2012/2013functionality: you can paste an XML source as Classes,in fact creating all the object model to serialize and

refs:

https://dennymichael.net/2014/05/30/convert-xml-to-csharp-classes/comment-page-1/


Today I foundacool Visual Studio 2012/2013functionality: you can paste an XML source as Classes,in fact creating all the object model to serialize anddeserialize object with the xml format,all this without usingxsd.exe tool.

Here’s the very simple steps:

1 – The most difficult step….. copy the xml source in the clipboard,something like CTRL+A and CTRL+C

Is ridiculous to add a screenshot,but I’ve got it,so why not!

2 – Create a new empy class file… no more screenshot please! ok here we go

3 – Go to Edit -> Paste Special -> Paste XML As Classes,to paste the generated classes based on the source xml

Here’s the code I’ve used to test thedeserialization:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using ConsoleDump;
using ConvertXmlToCSharpClasses.Properties;
namespace ConvertXmlToCSharpClasses
{
internal class Program
{
private static void Main( string [] args)
{
TestSample1();
TestSample2();
Console.WriteLine( "Press enter to exit the application..." );
Console.ReadLine();
}
private static void TestSample1()
{
var serializer = new XmlSerializer( typeof (library));
var buffer = Encoding.UTF8.GetBytes(Resources.Sample1);
using ( var stream = new MemoryStream(buffer))
{
var library = (library)serializer.Deserialize(stream);
library.book.Dump( "Book" );
library.book.title.Dump( "Book Title" );
library.book.author.Dump( "Book Title" );
}
}
private static void TestSample2()
{
var serializer = new XmlSerializer( typeof (catalog));
var buffer = Encoding.UTF8.GetBytes(Resources.Sample2);
using ( var stream = new MemoryStream(buffer))
{
var catalog = (catalog)serializer.Deserialize(stream);
catalog.product.Dump( "Product" ).catalog_item.Dump( "Product Items" )[0].size.Dump( "Item Size" )[0].color_swatch.Dump( "Color Swatch" );
}
}
}
}

You can also download the test project.

4 – Enjoy your savedtime

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读