如何反序列化的XMLDocument在C#中的对象? [英] How to Deserialize XMLDocument to object in C#?

查看:391
本文介绍了如何反序列化的XMLDocument在C#中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我接受 XML 字符串格式的.Net webserivce。 送进webserivce可以代表系统中的任何对象XML 字符串。我需要检查的第一个节点要弄清楚什么反对反序列化XML字符串。为此,我必须将XML加载到一个的XMLDocument (不要想用正则表达式或字符串比较)。我想知道如果有一种方法反序列化的XMLDocument /的XMLNode 宁可反序列化字符串以节省一些表现?是否有将是任何性能优势序列化的XMLNode ,而该字符串?

I have a .Net webserivce that accepts XML in string format. XML String sent into the webserivce can represent any Object in the system. I need to check the first node to figure out what object to deserialize the XML string. For this I will have to load the XML into an XMLDocument (Don't want to use RegEx or string compare). I am wondering if there is a way to Deserialize the XMLDocument/XMLNode rather that deserializing the string to save some performance? Is there going to be any performance benefit serializing the XMLNode rather that the string?

方法加载的XMLDocument

Method to Load XMLDocument

public void LoadFromString(String s)
{
    m_XmlDoc = new XmlDocument();
    m_XmlDoc.LoadXml(s);        
}



感谢

Thanks

推荐答案

如果你有一个的XmlDocument ,您可以用 XmlNodeReader对象的XmlReader 传递给的XmlSerializer ,但我不知道它会好做它的其他方式;使用的XmlReader 来得到最外层的元素名称,并给予的的XmlSerializer ..

If you have an XmlDocument, you can use XmlNodeReader as an XmlReader to pass to XmlSerializer, but I wonder if it would be better to do it the other way; use an XmlReader to get the outermost element name, and give that to XmlSerializer...

[XmlRoot("foo")]
public class Foo
{
    [XmlAttribute("id")]
    public int Id { get; set; }
}
static class Program
{
    static void Main()
    {
        string xml = "<foo id='123'/>";
        object obj;
        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            reader.MoveToContent();
            switch (reader.Name)
            {
                case "foo":
                    obj = new XmlSerializer(typeof(Foo)).Deserialize(reader);
                    break;
                default:
                    throw new NotSupportedException("Unexpected: " + reader.Name);
            }
        }            
    }
}

这篇关于如何反序列化的XMLDocument在C#中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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