从Xsd.exe使用XmlReader和类反序列化Xml

好的,我在尝试一些教程的同时尝试学习XmlSerializer遇到了麻烦.我已经执行了所有建议的步骤,但是我的程序未返回任何内容,或者返回null.我创建了一个XML文件,如下所示:

<?xml version='1.0' encoding='UTF-8' ?>
<WeeklyJobs>
   <DailyJobs Date = "02/03/2012"/>
  <DailyJobs Date = "02/04/2012" TotalJobs = "2">
    <Jobs>
      <Job JobName = "Job Name" Description = "Description"/>
      <Job JobName = "Job Name" Description = "Description"/>
    </Jobs>
  </DailyJobs>
  <DailyJobs Date = "02/05/2012" TotalJobs = "1">
    <Jobs>
      <Job JobName = "Job Name" Description = "Description"/>
    </Jobs>
  </DailyJobs>
  <DailyJobs Date = "02/06/2012" TotalJobs = "2">
    <Jobs>
      <Job JobName = "Job Name" Description = "Description"/>
      <Job JobName = "Job Name" Description = "Description"/>
    </Jobs>
  </DailyJobs>
  <DailyJobs Date = "02/07/2012"/>
  <DailyJobs Date = "02/08/2012" TotalJobs = "2">
    <Jobs>
      <Job JobName = "Job Name" Description = "Description"/>
      <Job JobName = "Job Name" Description = "Description"/>
    </Jobs>
  </DailyJobs>
</WeeklyJobs>

然后,我使用xsd.exe生成了.xsd文件,该文件是:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="WeeklyJobs" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="WeeklyJobs" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="DailyJobs">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Jobs" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="Job" minOccurs="0" maxOccurs="unbounded">
                      <xs:complexType>
                        <xs:attribute name="JobName" type="xs:string" />
                        <xs:attribute name="Description" type="xs:string" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="Date" type="xs:string" />
            <xs:attribute name="TotalJobs" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

创建架构后,我再次使用xsd.exe为我自动生成了以下类:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class WeeklyJobs
{

    private WeeklyJobsDailyJobs[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("DailyJobs", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public WeeklyJobsDailyJobs[] Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class WeeklyJobsDailyJobs
{

    private WeeklyJobsDailyJobsJobsJob[][] jobsField;

    private string dateField;

    private string totalJobsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlArrayItemAttribute("Job", typeof(WeeklyJobsDailyJobsJobsJob), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable = false)]
    public WeeklyJobsDailyJobsJobsJob[][] Jobs
    {
        get
        {
            return this.jobsField;
        }
        set
        {
            this.jobsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Date
    {
        get
        {
            return this.dateField;
        }
        set
        {
            this.dateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string TotalJobs
    {
        get
        {
            return this.totalJobsField;
        }
        set
        {
            this.totalJobsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class WeeklyJobsDailyJobsJobsJob
{

    private string jobNameField;

    private string descriptionField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string JobName
    {
        get
        {
            return this.jobNameField;
        }
        set
        {
            this.jobNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Description
    {
        get
        {
            return this.descriptionField;
        }
        set
        {
            this.descriptionField = value;
        }
    }
}

此后,我将.CS文件添加到我的项目中,并使用文本框创建了一个简单的winform,以在反序列化某些xml后显示一些数据.就像我说的那样,程序启动后,TextBox中什么也不显示,也没有抛出异常.这是我的winform:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public string getExample()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(WeeklyJobs));
        WeeklyJobs jobs;
        string xml = @"<?xml version = ""1.0""?>"
            + @"<WeeklyJobs>"
            + @"<DailyJobs Date = ""02/03/2012""/>"
            + @"<DailyJobs Date = ""02/04/2012"" TotalJobs = ""2"">"
            + @"<Jobs>"
            + @"<Job JobName = ""Job Name"" Description = ""Description""/>"
            + @"<Job JobName = ""Job Name"" Description = ""Description""/>"
            + @"</Jobs>"
            + @"</DailyJobs>"
            + @"</WeeklyJobs>";

        // Create an XmlTextReader
        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            jobs = (WeeklyJobs)serializer.Deserialize(reader);
        }

        return jobs.Items[0].Date;

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.Text = getExample();

    }


}

我有很多更简单的xml示例可以使用,但是第二次尝试为我的xml添加一些复杂性,但我失败了.我必须弄清楚如何使用这里的xml.感谢您的帮助!感谢大家!

解决方法:

好的,第一个问题是XmlSerializer构造函数正在引发未处理的异常,但是某种程度上它被吞噬了.这解释了为什么文本框为空.我将调试器设置为在所有CLR异常上均中断,并发现构造函数引发了InvalidOperationException-显然是在代码生成过程中:

Unable to generate a temporary class (result=1).

error CS0030: Cannot convert type ‘DeleteMe.WeeklyJobsDailyJobsJobsJob[]’ to ‘DeleteMe.WeeklyJobsDailyJobsJobsJob’

error CS0029: Cannot implicitly convert type ‘DeleteMe.WeeklyJobsDailyJobsJobsJob’ to ‘DeleteMe.WeeklyJobsDailyJobsJobsJob[]’

(构造函数还抛出了FileNotFound异常,但它也可以处理该异常,因此您可以忽略它.)

似乎问题出在锯齿状阵列中-您是否将一维阵列更改为锯齿状阵列?当然,该错误消息向我指出了这个方向,但是我也从未在xsd生成的代码中见过锯齿状的数组,因此它看起来很可疑.我将两次出现的WeeklyJobsDailyJobsJobsJob [] []更改为WeeklyJobsDailyJobsJobsJob [],该应用程序运行正常.

顺便说一句,您应该使用DateTime作为日期,但是XML序列化器不支持可变日期格式(请参见https://*.com/a/1118855/385844).如果您无法控制源,则最好将字符串转换为日期,然后再将其存储在数据库中或任何位置.

上一篇:为什么XmlReader跳过元素?


下一篇:Qt 实现读写xml