通常,我为我的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; } }} 最佳答案 如果从数据库以字符串形式获取XML,则可以使用StringReader。或者,如果您获得byte[],则可以尝试MemoryStream。[WebMethod]public dsXmlSummary getXML(){ TextReader reader = new StringReader("<dsXmlSummary><FirstName>Mark</FirstName></dsXmlSummary>"); dsXmlSummary ds = (dsXmlSummary)serializer.Deserialize(reader); reader.Close();}关于“手动”示例,您需要初始化Items数组。添加了xml.Items[0] = new YourItemsType(); [WebMethod]public dsXmlSummary getXML(){ dsXmlSummary xml = new dsXmlSummary(); xml.Items = new YourItemsType[1]; // <-- initialize here xml.Items[0] = new YourItemsType(); // <-- initialize first object 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;}关于c# - C#如何填充从数据库使用XSD.EXE创建的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3664347/
10-09 21:58