使用XmlReader和xsd.exe中的类反序列化Xml [英] Deserialize Xml Using XmlReader and Class from xsd.exe

查看:93
本文介绍了使用XmlReader和xsd.exe中的类反序列化Xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 <?xml version ='1.0'encoding ='UTF-8'?> ; 
< WeeklyJobs>
< DailyJobs Date = 02/03/2012 />
< DailyJobs日期= 02/04/2012 TotalJobs = 2>
< Jobs>
< Job JobName =职位名称 Description =描述 />
< Job JobName =职位名称 Description =描述 />
< / Jobs>
< / DailyJobs>
< DailyJobs日期= 02/05/2012 TotalJobs = 1>
< Jobs>
< Job JobName =职位名称 Description =描述 />
< / Jobs>
< / DailyJobs>
< DailyJobs日期= 02/06/2012 TotalJobs = 2>
< Jobs>
< Job JobName =职位名称 Description =描述 />
< Job JobName =职位名称 Description =描述 />
< / Jobs>
< / DailyJobs>
< DailyJobs Date = 02/07/2012 />
< DailyJobs日期= 02/08/2012 TotalJobs = 2>
< Jobs>
< Job JobName =职位名称 Description =描述 />
< Job JobName =职位名称 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 =作业 minOccurs = 0 maxOccurs = unbounded>
< xs:complexType>
< xs:sequence>
< xs:element name =作业 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为我自动生成了以下类: / p>

  ///<备注/> 
[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)]
公共局部类WeeklyJobs
{

private WeeklyJobsDailyJobs [] itemsField;

///<备注/>
[System.Xml.Serialization.XmlElementAttribute( DailyJobs,Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public WeeklyJobsDailyJobs []项目
{
get
{
返回this.itemsField;
}
set
{
this.itemsField = value;
}
}
}

///<备注/>
[System.CodeDom.Compiler.GeneratedCodeAttribute( xsd, 2.0.50727.3038)]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( code)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
公共局部类WeeklyJobsDailyJobs
{

私人WeeklyJobsDailyJobsJobsJob [] [] jobsField;

私有字符串dateField;

私有字符串totalJobsField;

///<备注/>
[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)]
公共WeeklyJobsDailyJobsJobsJob [] []工作
{
get
{
返回this.jobsField;
}
set
{
this.jobsField = value;
}
}

///<备注/>
[System.Xml.Serialization.XmlAttributeAttribute()]
公共字符串日期
{
get
{
返回this.dateField;
}
set
{
this.dateField = value;
}
}

///<备注/>
[System.Xml.Serialization.XmlAttributeAttribute()]
公共字符串TotalJobs
{
get
{
返回this.totalJobsField;
}
set
{
this.totalJobsField = value;
}
}
}

///<备注/>
[System.CodeDom.Compiler.GeneratedCodeAttribute( xsd, 2.0.50727.3038)]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( code)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
公共局部类WeeklyJobsDailyJobsJobsJob
{

私有字符串jobNameField;

私有字符串descriptionField;

///<备注/>
[System.Xml.Serialization.XmlAttributeAttribute()]
公共字符串JobName
{
get
{
返回this.jobNameField;
}
set
{
this.jobNameField = value;
}
}

///<备注/>
[System.Xml.Serialization.XmlAttributeAttribute()]
公共字符串说明
{
get
{
返回this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
}

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

 公共部分类Form1:Form 
{
public Form1()
{
InitializeComponent();

}

公共字符串getExample()
{
XmlSerializer serializer = new XmlSerializer(typeof(WeeklyJobs));
WeeklyJobs职位;
字符串xml = @<?xml version = 1.0?>
+ @< WeeklyJobs>
+ @< DailyJobs Date = 02/03/2012 />
+ @< DailyJobs Date = 02/04/2012 TotalJobs = 2>
+ @< Jobs>
+ @< Job JobName =职位名称 Description =描述 />
+ @< Job JobName =职位名称 Description =描述 />
+ @< / Jobs>
+ @< / DailyJobs>
+ @< / WeeklyJobs>;

//使用(XmlReader reader = XmlReader.Create(new StringReader(xml)))创建XmlTextReader

{
jobs =(WeeklyJobs)serializer.Deserialize (读者);
}

个返回工作。Items[0] .Date;

}

私人无效Form1_Load(对象发送者,EventArgs e)
{
textBox1.Text = getExample();

}


}

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

解决方案

好吧,第一个问题是XmlSerializer构造函数正在引发未处理的异常,但是以某种方式被吞噬了。这解释了为什么文本框为空。我将调试器设置为在所有CLR异常上均中断,并发现构造函数抛出了InvalidOperationException异常-显然是在代码生成过程中: >无法生成临时类(结果= 1)。



错误CS0030:无法将类型 DeleteMe.WeeklyJobsDailyJobsJobsJob []转换为 DeleteMe.WeeklyJobsDailyJobsJobsJob



错误CS0029:无法将类型'DeleteMe.WeeklyJobsDailyJobsJobsJob'隐式转换为'DeleteMe.WeeklyJobsDailyJobsJobsJob []'


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



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



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


OK I have hit a snag trying to learn XmlSerializer while going through some tutorials. I have followed all the recommended steps but my program is not returning anything, or is returning null. I created an XML file as follows:

<?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:

<?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:

/// <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. Like I said the program launches and nothing is displayed in the TextBox and no Exceptions are thrown. Here is my 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. I have to figure out how to use the xml I have here. 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. 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:

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[]'

(The constructor was also throwing a FileNotFound exception, but it also handles that, so you can ignore it.)

It seems the problem is the jagged arrays -- did you change 1-dimensional arrays to jagged arrays? 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. I changed two occurrences of WeeklyJobsDailyJobsJobsJob[][] to WeeklyJobsDailyJobsJobsJob[] and the application worked just fine.

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). 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.

这篇关于使用XmlReader和xsd.exe中的类反序列化Xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆