c# - 使 xsd.exe 实用程序生成具有强类型的架构
问题描述
我有这个示例 XML 文件:
<?xml version="1.0"?>
<DocumentElement>
<item>
<id>1</id>
<name>BBB</name>
</item>
<item>
<id>2</id>
<name>BBB</name>
</item>
</DocumentElement>
我想使用 xsd.exe 实用程序生成 XSD 架构并运行以下命令:
xsd.exe myXmlFile.xml
这是我得到的输出:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="DocumentElement" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="DocumentElement" msdata:IsDataSet="true" msdata:Locale="en-US">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string" minOccurs="0" />
<xs:element name="name" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
请注意,这两个字段都是字符串,但我希望它们是整数和字符串。
如果我在 VS 中生成模式,那么我会得到更好的结果:
<xs:element name="id" type="xs:unsignedByte" />
<xs:element name="name" type="xs:string" />
如何让 xsd.exe 像在 VS 中一样工作?
解决方案
您可以尝试以下步骤来生成具有强类型的 xsd 文件。
首先,请使用以下命令生成 xsd 文件:
xsd D:\Sample.xml /outputdir:D:\
其次,请从xsd文件生成一个类:
xsd D:\Sample.xsd /classes /outputdir:D:\
第三,请创建一个类库(.net framework 3.5)并将生成的类添加到项目中,重建它。
四、关于id,请将string类型改为int类型。
公共部分类 DocumentElementItem {
private int idField; //Change string to int
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int id { //Change string to int
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
最后,请使用以下命令生成强类型的 xsd 文件。
xsd "D:\Test\bin\Debug\Test.dll" /type:DocumentElementItem /outputdir:D:\
您将获得以下 xsd 文件。
此外,您可以在下图中看到所有过程。
推荐阅读
- python-3.x - 我安装了 cv2,当我使用级联分类器类运行代码时,它显示模块“cv2”没有属性“CascadeClassifier”
- node.js - 为什么这个 Alexa 自定义技能在 Nodejs 中的 Lambda 不起作用(Alexa 不说话,超时)
- spring-boot - Zuul Gateway 服务器在本地处理请求
- python - Python 2 和 Python 3 中不同类型的内部类
- python - 在 PySpark 中将 StringType 列转换为 ArrayType
- excel - MDX 从 Excel 2010/Excel 365 (16.0.11328.20363) 更改行为
- python - 如何在 Python 中使用 break 语句退出嵌套的 for 循环
- vue.js - 如何在 Vue 中全局导入我自己的类或方法?
- node.js - Twilio - 了解呼出电话是否由接收者转移
- idris - 为什么 Idris 给我以下代码的类型不匹配错误?