使用 XSD 文件生成 XML 文件 [英] Generating XML file using XSD file
本文介绍了使用 XSD 文件生成 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 XSD 文件生成 XML 文件?
How do you generate an XML file from an XSD file?
推荐答案
假设我们有如下所示的 Test.xsd 文件:
Suppose we have Test.xsd file that looks like this:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyClass">
<xs:complexType>
<xs:sequence>
<xs:element name="Field1"
type="xs:string"/>
<xs:element name="Field2"
type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
使用 xsd 工具创建类:
Create classes using xsd tool:
xsd.exe /classes Test.xsd
这将生成 Test.cs 文件.
This will generate Test.cs file.
将 Test.cs 文件添加到您的解决方案中.
Add Test.cs file to your solution.
创建 MyClass
的实例,在 XSD 架构中定义,并将其 XmlSerialize:
Create instance of MyClass
, defined in XSD schema and XmlSerialize it:
using System.Xml.Serialization;
// ...
var data = new MyClass { Field1 = "test1", Field2 = "test2" };
var serializer = new XmlSerializer(typeof(MyClass));
using (var stream = new StreamWriter("C:\test.xml"))
serializer.Serialize(stream, data);
结果:
<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Field1>test1</Field1>
<Field2>test2</Field2>
</MyClass>
这篇关于使用 XSD 文件生成 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文