简体   繁体   中英

How to Deserialize XMLDocument to object in C#?

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?

Method to Load XMLDocument

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

Thanks

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);
            }
        }            
    }
}

Don't forget a powerfull contender, LINQ to XML!

XElement root = XElement.Load(myfile);

var foos = root.Descendants("Foo").Where(e => e.Attribute("bar") != null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM