How to Deserialize XMLDocument to object in C#?

后端 未结 2 1739
名媛妹妹
名媛妹妹 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 = "<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);
                }
            }            
        }
    }
    
    0 讨论(0)
  • 2021-02-15 18:46

    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);
    
    0 讨论(0)
提交回复
热议问题