通用XML反序列化为未定义对象 [英] Generic XML Deserialization into Undefined Objects

查看:47
本文介绍了通用XML反序列化为未定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常长的,非常多样化的XML文件,我试图将其中的一部分存储到数据库中.现在,我不想遍历和手写10,000个不同的对象来存储反序列化的数据.有什么方法可以基于XML文件中的内容来定义对象?

I have a very long, very varied XML file that I am attempting to store portions of into a database. Now, I do not want to go through and hand-write 10,000 different objects to store the deserialized data into. Is there any way to define an Object based on what is found in the XML file?

例如,如果我有:

<objecttype1>
    <attr1>Some string of text</attr1>
</objecttype1>
<objecttype1>
    <attr2>123456789</attr2>
</objecttype1>

我希望定义类似于以下内容的对象:

I would want an object similar to the following to be defined:

public class objecttype1 {
    public string attr1 {get; set;}
    public string attr2 {get; set;}
}

基本上,我想将整个xml文档反序列化为具有表示原始xml文档的某种层次结构的各种不同对象,然后从这些对象中提取数据,然后根据它们的类型放入我的数据库中.有什么方法/更好的方法吗?

Basically, I want to deserialize the entire xml document into a variety of different objects with some sort of hierarchical structure representing the original xml document, and then extract data from those objects to put into my database based on their type. Is there any way/a better way to do this?

推荐答案

您正在寻找此处找到的示例实现:

You're looking for an ExpandoObject.
ExpandoObject is a dynamic object introduced in C#4.
Sample implementation found here:

 public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid)
{
    var expandoFromXml = new List<dynamic>();

    var doc = XDocument.Load(file);
    var nodes = doc.Root.Descendants(descendantid);

    foreach (var element in doc.Root.Descendants(descendantid))
    {
        dynamic expandoObject = new ExpandoObject();
        var dictionary = expandoObject as IDictionary<string, object>;
        foreach (var child in element.Descendants())
        {
            if (child.Name.Namespace == "")
                dictionary[child.Name.ToString()] = child.Value.Trim();
        }
        yield return expandoObject;
    }
}

更多链接:
http://www.codeproject.com/Tips/227139/将XML转换为使用ExpandoO的动态对象
http://www.codeproject.com/Articles/461677/从XML-使用ExpandoOb创建动态对象

这篇关于通用XML反序列化为未定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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