Skip to main content
 首页 » 编程设计

C# 如何从数据库中填充使用 XSD.EXE 创建的类

2024年02月24日23xing901022

通常我会编写一个类并为我的 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] 
    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; 
}