How to Deserialize XMLDocument to object in C#?

后端 未结 2 1730
名媛妹妹
名媛妹妹 2021-02-15 18:17

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-15 18:35

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

提交回复
热议问题