c# - 通过 DataContract 序列化到 XML Writer

标签 c# linq-to-entities xml-serialization datacontractserializer

我是 .NET 的新手,但从事这个项目已经有一段时间了,但进展甚微,而且随着类(class)数量的增加,我有点不知所措。

目标:

  1. 从 Entity Framework 表生成数据(应该使用 LINQ)<- LINQ 似乎可以正常工作。

  2. 将数据转换为 XML <-根本不起作用

  3. 如果不起作用,请发送电子邮件 <- 这工作得很好——奇怪的是,哈哈;)

谁能给我一个代码示例,您可以在其中通过 DataContract 连接到实体并序列化(如果这是最好的方法,则可能使用泛型)到 XML 编写器?根据评论,这里是我想要的示例。 -- 所以我们还要说,在这个模型中,我们想要加入“DIRTYMIKE”表,其中包括“The Boys”作为一个对象,其名称将通过 xml 和 PRIUS 中的“CARS”表通过 id 提取。显然这是一个理论上的一组实体,但希望它能让某人发笑 :)

这是我刚刚准备的一些理论课 - 希望这能更多地解释目标是什么:

 public class TheOtherGuys 
{
    private static ILog log;
    private string theBoysWrapper;
    private int rowsRead = 0;
    private int outputRecords = 0;
    private bool warnings = false;
    private bool fatal = false;
    private bool fatalMsg = false;
    /// <summary>
    /// Next wrap the xml with a Document Wrapper and Element Wrapper
    /// </summary>
   public TheOtherGuys(ILog log)
    {

        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);//creates root
        XmlElement root = doc.CreateElement("DIRTYMIKE");
        doc.AppendChild(root);
        XmlElement nextElem = doc.CreateElement("THEBOYS");
        log = LogManager.GetLogger(this.GetType());
        if (log.IsDebugEnabled == true)
        {
            log.Debug(GetType().Name + ".Constructor(): enter");
        }
        //creates new xml Document and set up declaration and root

        if (log.IsDebugEnabled == true)
        {
            log.Debug(GetType().Name + ".Constructor(): exit");
        }
    }
    //Read data from DIRTY_MIKE_AND_THE_BOYS and CAR Tables
    //Translate the results into xml
    private void process(DateTime process) {

        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);//creates root
        XmlElement root = doc.CreateElement("OTHERGUYS");//maybe  a conditional statement to          change the root to 'OTHERGUYS'
        doc.AppendChild(root);
        XmlElement nextElem = doc.CreateElement("CAR");
        doc.AppendChild(nextElem);

        if (log.IsDebugEnabled == true)
        {
            log.Debug(GetType().Name + ".process(): enter - prius=" + process);
        }
        StringBuilder sb = new StringBuilder();
        sb.Append(" select ");
        sb.Append("     'PRIUS' CAR, ");  // 1
        sb.Append("     'PJM' MKT_CD, ");      // 2
        sb.Append("     decode(to_char(lh.time_id-1/24, 'HH24'), '00',  ");
        sb.Append("            to_char(lh.time_id-1, 'YYYYMMDD'), to_char(lh.time_id-1/24, 'YYYYMMDD')) START_DT, ");   // 3
        sb.Append("     decode(to_char(lh.time_id-1/24, 'HH24'), '00',  ");
        sb.Append("            '240000', to_char(lh.time_id-1/24, 'HH24MISS')) START_TIME, "); //4
        sb.Append("     decode(to_char(lh.time_id, 'HH24'), '00',  ");
        sb.Append("            to_char(lh.time_id-1, 'YYYYMMDD'), to_char(lh.time_id, 'YYYYMMDD')) END_DT, ");  // 5
        sb.Append("     decode(to_char(lh.time_id, 'HH24'), '00',  ");
        sb.Append("            '240000', to_char(lh.time_id, 'HH24MISS')) END_TIME,      ");  // 6
        sb.Append("       cars._car_id            TX_PT,     ");  //8
        sb.Append("     lh.data_value TARGET_FD ");  // 12
        sb.Append("from DATABASE.MYTABLE lh,          ");
        sb.Append("     DATABASE.CAR car_id                         ");
        sb.Append("where lh.car_id = unit.car_id         ");
        sb.Append("AND lh.time_id > to_date(?, 'MM/DD/YYYY') ");
        sb.Append("AND lh.time_id <= to_date(?, 'MM/DD/YYYY' ) + 1 ");
        sb.Append("AND lh.atb_data_category = 69  AND lh.data_value <> 0        ");
        sb.Append(" order by ");
        sb.Append("     lh.time_id, lh.car_id ");

        sb.ToString();// or something like that 
       myDataLayer.theOtherGuysEntitie nme = new myDataLayer.theOtherGuysEntities(myConnection.getEntityFrameworkConnection(typeof(myDataLayer.theOtherGuysEntities)));
        if (log.IsDebugEnabled == true)
        {
            log.Debug(GetType().Name + ".process(): odb" + odb);
            try
            {
                DateTime dt = DateTime.ParseExact(processingDate.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
                string s = dt.ToString("dd/M/yyyy");



            }catch(Exception e) {
                fatal=true;
                fatalMsg = true;
                if(log.IsFatalEnabled==true) {
                    log.Fatal(GetType().Name + ".process(): exception", e);
                }
                Console.Error.WriteLine("The OtherGuys Failed Dirty Mike is in the Prius with name{}, name{1}, name{2}, name {3}.");
     //Really I am supposed to use LINQ for the querying
    // and then conditionalstatementsthrough my business logic to handle the decoding 

再次感谢!!

最佳答案

public static string ToXmlUsingDataContract<T>(T obj)
{
    var dcs = new DataContractSerializer(typeof(T));
    var sb = new StringBuilder();

    using (var writer = XmlWriter.Create(sb))
    {
        dcs.WriteObject(writer, obj);
    }

    return (sb.ToString());
}

只需创建某种数据传输对象,或直接将实体对象传递给此函数,您将获得有效的、可反序列化的 XML。

关于c# - 通过 DataContract 序列化到 XML Writer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15796619/

相关文章:

c# - 线程问题

c# - 从 WCF 中获取一个大的 List<T> block ?

C#密码加密

c# - Active Directory - 确定域的唯一 ID

c# - LINQ to SQL 在更新后返回旧数据

java - JAXB "If a class has @XmlElement property, it cannot have @XmlValue property."

c# - LINQ to SQL 如何知道委托(delegate)中有什么?

c# - 将数组加入 EF 查询

c# - DTO 的自定义数组项名称

C# XmlSerializer 强制编码类型为 ISO-8859-1