通常,我编写一个类,并为我的Web服务向它添加XML序列化。
[XmlRootAttribute(ElementName = "dsXmlSummary", IsNullable=true)]
public class Class1
{
//declare properties
//make database calls to pull data and load properties
}
我正在开发一个项目,这个项目要求我使用严格的XSD,我遵循了使用xsd.exe工具创建基于XSD的类的说明。我的解释是,这个自动生成的类将替换我的普通序列化类。
如果是这种情况,那么在将数据加载到类属性中时,我将完全丢失。
我从另一个演练中收集到:
[WebMethod]
public dsXmlSummary getXML()
{
TextReader reader = new StreamReader("data.xml");
dsXmlSummary ds = (dsXmlSummary)serializer.Deserialize(reader);
reader.Close();
}
但是,我所拥有的数据位于一个SQL数据库中…我认为我应该能够编写一个方法来填充
dsXmlSummary
但是,我找不到任何有关这样做的文档。所有的例子都与上面一样,从实际的物理XML文档中加载或读取。
我试过测试手动加载:
[WebMethod]
public dsXmlSummary getXML()
{
dsXmlSummary xml = new dsXmlSummary();
xml.Items[0].nameFirst = "Mark"; //error thrown here: System.NullReferenceException: Object reference not set to an instance of an object.
xml.Items[0].nameLast = "Twain";
xml.Items[0].Type = "Writer";
return xml;
}
显然,我这一切都错了。任何指导都非常感谢。
编辑
我的WebMethod
[WebMethod]
public dsXmlSummary getXML()
{
dsXmlSummary xml = new dsXmlSummary();
dsXmlSummaryAdmin_reports_xmlReports[] items = new dsXmlSummaryAdmin_reports_xmlReports[1];
items[0].nameFirst = "Mark"; //error still thrown here: System.NullReferenceException: Object reference not set to an instance of an object.
items[0].nameLast = "Twain";
items[0].Type = "Writer";
xml.Items = items;
return xml;
}
自动生成的类
public partial class dsXmlSummary {
private dsXmlSummaryAdmin_reports_xmlReports[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("admin_reports_xmlReports")]
public dsXmlSummaryAdmin_reports_xmlReports[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}