简体   繁体   English

使用xsd.exe中的XmlReader和Class反序列化Xml

[英]Deserialize Xml Using XmlReader and Class from xsd.exe

OK I have hit a snag trying to learn XmlSerializer while going through some tutorials. 好的,我在尝试学习XmlSerializer的过程中遇到了一些障碍。 I have followed all the recommended steps but my program is not returning anything, or is returning null. 我已经遵循了所有建议的步骤,但我的程序没有返回任何内容,或者返回null。 I created an XML file as follows: 我创建了一个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>

I then used xsd.exe to generate the .xsd file which is: 然后我使用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>

After creating the schema I used xsd.exe again to auto generate the class for me which is: 创建架构后,我再次使用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;
        }
    }
}

After this I added the .CS file to my project and created a simple winform with a TextBox to display some data once I have deserialized some xml. 在此之后,我将.CS文件添加到我的项目中,并创建了一个带有TextBox的简单winform,以便在我对一些xml进行反序列化后显示一些数据。 Like I said the program launches and nothing is displayed in the TextBox and no Exceptions are thrown. 就像我说程序启动一样,TextBox中没有显示任何内容,也没有抛出异常。 Here is my winform: 这是我的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();

    }


}

I have got much more simple xml examples to work but I the second I try to add some complexity to my xml I fail. 我有更简单的xml示例可以工作,但我第二次尝试为我的xml添加一些复杂性我失败了。 I have to figure out how to use the xml I have here. 我必须弄清楚如何使用我在这里的xml。 I appreciate the help! 我很感激帮助! Thanks everyone! 感谢大家!

Ok, the first problem is that the XmlSerializer constructor is raising an unhandled exception, but that is somehow getting swallowed. 好吧,第一个问题是XmlSerializer构造函数正在引发一个未处理的异常,但这是以某种方式被吞噬。 This explains why the text box is empty. 这解释了文本框为空的原因。 I set the debugger to break on all CLR exceptions, and found that the constructor was throwing an InvalidOperationException -- apparently during the code generation process: 我将调试器设置为中断所有CLR异常,并发现构造函数抛出InvalidOperationException - 显然是在代码生成过程中:

Unable to generate a temporary class (result=1). 无法生成临时类(result = 1)。

error CS0030: Cannot convert type 'DeleteMe.WeeklyJobsDailyJobsJobsJob[]' to 'DeleteMe.WeeklyJobsDailyJobsJobsJob' 错误CS0030:无法将类型'DeleteMe.WeeklyJobsDailyJobsJobsJob []'转换为'DeleteMe.WeeklyJobsDailyJobsJobsJob'

error CS0029: Cannot implicitly convert type 'DeleteMe.WeeklyJobsDailyJobsJobsJob' to 'DeleteMe.WeeklyJobsDailyJobsJobsJob[]' 错误CS0029:无法将类型'DeleteMe.WeeklyJobsDailyJobsJobsJob'隐式转换为'DeleteMe.WeeklyJobsDailyJobsJobsJob []'

(The constructor was also throwing a FileNotFound exception, but it also handles that, so you can ignore it.) (构造函数也抛出了一个FileNotFound异常,但它也会处理它,所以你可以忽略它。)

It seems the problem is the jagged arrays -- did you change 1-dimensional arrays to jagged arrays? 似乎问题是锯齿状数组 - 你是否将1维数组更改为锯齿状数组? The error message pointed me in that direction, of course, but I have also never seen jagged arrays in xsd-generated code, so it looked suspicious. 当然,错误消息指出了我的方向,但我也从未在xsd生成的代码中看到过锯齿状数组,因此看起来很可疑。 I changed two occurrences of WeeklyJobsDailyJobsJobsJob[][] to WeeklyJobsDailyJobsJobsJob[] and the application worked just fine. 我将WeeklyJobsDailyJobsJobsJob[][]两次出现更改为WeeklyJobsDailyJobsJobsJob[]并且应用程序工作得很好。

As an aside, you should use DateTime for your dates, but XML serializer does not support variable date formats (see https://stackoverflow.com/a/1118855/385844 ). 另外,您应该使用DateTime作为日期,但XML序列化程序不支持可变日期格式(请参阅https://stackoverflow.com/a/1118855/385844 )。 If you have no control over the source, you're probably better off converting the strings to dates before you store them in your database or wherever. 如果您无法控制源,那么在将字符串存储到数据库或任何地方之前,最好将字符串转换为日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM