More info here: http://blogs.msdn.com/b/yojoshi/archive/2011/05/14/xml-serialization-and-deserialization-entity-classes-with-xsd-exe.aspx

Introduction

Many time we come across the need of parsing XML document and creating entities. These entities are later passed between multiple methods, stored as configuration or used to perform some manipulation. Hand wrting code for parsing these entities from XML document is tedious. This article presents and easy way to parse XML documents and generating deserializers.

Hands on!

Lets create a sample XML document named Students.xml following is the sample content.

<xml version="1.0" encoding="utf-8" ?>
<Students>
<Student>
<RollNo>1</RollNo>
<Name>Student 1</Name>
<Address>Xyz Street</Address>
</Student>
<Student>
<RollNo>2</RollNo>
<Name>Student 2</Name>
<Address>Xyz Street</Address>
</Student>
<Student>
<RollNo>3</RollNo>
<Name>Student 3</Name>
<Address>Xyz Street</Address>
</Student>
<Student>
<RollNo>4</RollNo>
<Name>Student 4</Name>
<Address>Xyz Street</Address>
</Student>
<Student>
<RollNo>5</RollNo>
<Name>Student 5</Name>
<Address>Xyz Street</Address>
</Student>
</Students>

Here, as we can see, there is one root node named <Students> and it contains <Student> nodes as children. Now, what if we need to create a list of students in our program and bind it to some grid? We have to write manual parsing code for achieving same. But, you can easily achieve this task using xsd.exe to generate de-serializer and get the student collection. Following are the steps

  1. Start Visual Studio and open Student.xml
  2. Click on "XML" -> "Create Schema" on toolbar

  3. It will generate XML Schema. Following is the sample schema generated for Students.xml file
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Students">
    <xs:complexType>
    <xs:sequence>
    <xs:element maxOccurs="unbounded" name="Student">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="RollNo" type="xs:unsignedByte" />
    <xs:element name="Name" type="xs:string" />
    <xs:element name="Address" type="xs:string" />
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:schema>

  4. Here we can observe the datatypes are automatically set as per the data available in Student.xml As per your need you can edit the schema and set the appropriate data types.
  5. Save the Students.xml and Students.xsd files inside some folder say "C:\Sample\XML"
  6. Now, we have to start "Visual Studio Command Prompt"
  7. On VS Command Prompt, cd to "C:\Sample\XML" directory and type "xsd Students.xsd /c"

  8. This will generate "Students.cs" file that we can use to de-serialize Student.xml file
  9. Now create a "Console Application" named "XmlDeSerializer" we will use this to test the de-serialization
  10. Add "Students.cs" file that we have created using xsd.exe file

  11. Copy and paste following code in Program.cs file and run the program.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.IO;
    using System.Xml.Serialization; namespace XmlDeSerializer
    {
    class Program
    {
    static void Main(string[] args)
    {
    using (FileStream xmlStream = new FileStream("C:\\Sample\\XML\\Students.xml", FileMode.Open))
    {
    using (XmlReader xmlReader = XmlReader.Create(xmlStream))
    {
    XmlSerializer serializer = new XmlSerializer(typeof(Students));
    Students deserializedStudents = serializer.Deserialize(xmlReader) as Students;
    foreach (var student in deserializedStudents.Student)
    {
    Console.WriteLine("Roll No : {0}", student.RollNo);
    Console.WriteLine("Name : {0}", student.Name);
    Console.WriteLine("Address : {0}", student.Address);
    Console.WriteLine("");
    }
    }
    }
    }
    }
    }
  12. You will see following output

In this way we have successfully de-serialized Students.xml file and created entities. You May also serialize existing entites back in the xml format, we can use "Serialize" method of XmlSerializer.

Auto generating Entity classes with xsd.exe for XML Serialization and De-Serialization的更多相关文章

  1. 利用Vistual Studio自带的xsd.exe工具,根据XML自动生成XSD

    利用Vistual Studio自带的xsd.exe工具,根据XML自动生成XSD 1, 命令提示符-->找到vs自带的xsd.exe工具所在的文件夹 例如: C:\Program Files ...

  2. xsd.exe的使用

    xsd.exe的使用 XML文件生成XSD文件 xsd myFile.xml   /outputdir:myOutputDir XSD文件生存实体类 xsd <你的XSD路径>.xsd / ...

  3. 使用 xsd.exe 命令工具将 xsd 架构生成 类(CS) 文件

    vs自带命令行工具 命令:xsd  xml文件路径 C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC>xsd d:Scheme.xml ...

  4. 如何由XSD自动生成XML和实体类

    项目中有时候要用XML作为数据源,因此需要定义XML文件和相应的类,最佳方法是首先定义XSD,然后自动生成实体类,最后生成XML和填充数据:读取XML数据源的时候,首先用XSD验证XML数据格式,然后 ...

  5. XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式

    XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD),作用是定义 XML 文档的合法构建模块,类似 DTD,但更加强大. 作用有: ①定义 ...

  6. C# 使用xsd文件验证XML 格式是否正确

    C# 使用xsd文件验证XML 格式是否正确 核心示例代码: //创建xmlDocument XmlDocument doc = new XmlDocument(); //创建声明段 如<?xm ...

  7. 28.XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式

    转自https://www.cnblogs.com/gdjlc/archive/2013/09/08/3308229.html XML Schema 语言也称作 XML Schema 定义(XML S ...

  8. DELPHI中调用XSD去验证XML的合法性

    procedure TFrmPrintReport.Button3Click(Sender: TObject);var  SchemaDoc, XmlDoc: IXMLDOMDocument2;  S ...

  9. Spring如何加载XSD文件(org.xml.sax.SAXParseException: Failed to read schema document错误的解决方法)

    今天配置Spring的xml出现了错误 Multiple annotations found at this line: - schema_reference.4: Failed to read sc ...

随机推荐

  1. 【BZOJ 4515】【SDOI 2016 Round1 Day1 T3】游戏

    考场上写了lct,可惜当时对标记永久化的理解并不是十分深刻,导致调一个错误的程序调了4h+,最后这道题爆0了QwQ 现在写了树链剖分,用标记永久化的线段树维护轻重链,对于$s\rightarrow l ...

  2. 【BZOJ 3053】The Closest M Points

    KDTree模板,在m维空间中找最近的k个点,用的是欧几里德距离. 理解了好久,昨晚始终不明白那些“估价函数”,后来才知道分情况讨论,≤k还是=k,在当前这一维度距离过线还是不过线,过线则要继续搜索另 ...

  3. 欧拉函数 &【POJ 2478】欧拉筛法

    通式: $\phi(x)=x(1-\frac{1}{p_1})(1-\frac{1}{p_2})(1-\frac{1}{p_3}) \cdots (1-\frac{1}{p_n})$ 若n是质数p的k ...

  4. hdu4725最短路变形 添加点

    The Shortest Path in Nya Graph Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ...

  5. 【Codeforces 723C】Polycarp at the Radio 贪心

    n个数,用最少的次数来改变数字,使得1到m出现的次数的最小值最大.输出最小值和改变次数以及改变后的数组. 最小值最大一定是n/m,然后把可以改变的位置上的数变为需要的数. http://codefor ...

  6. 【Codeforces 707C】Pythagorean Triples(找规律)

    一边长为a的直角三角形,a^2=c^2-b^2.可以发现1.4.9.16.25依次差3.5.7.9...,所以任何一条长度为奇数的边a,a^2还是奇数,那么c=a^2/2,b=c+1.我们还可以发现, ...

  7. 【BZOJ-4316】小C的独立集 仙人掌DP + 最大独立集

    4316: 小C的独立集 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 57  Solved: 41[Submit][Status][Discuss] ...

  8. ubuntu中maven建的web项目不能将project facet设置为 dynamic web module 3.0

    核心参考:maven 不能设置为web3.0人解决方法 error:Description    Resource    Path    Location    Type Cannot change ...

  9. UOJ264 【NOIP2016】蚯蚓

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...

  10. 认识http协议

    http:Hyper Text Transfer Protocol,超文本传输协议.是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准.设计HTTP最初的目的是为了提供一种发布和 ...