首页 > 解决方案 > 使 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 中一样工作?

标签: c#xmlvisual-studio

解决方案


您可以尝试以下步骤来生成具有强类型的 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 文件。

在此处输入图像描述

此外,您可以在下图中看到所有过程。

在此处输入图像描述


推荐阅读