Deserialize Xml with empty elements

前端 未结 2 1703
甜味超标
甜味超标 2020-12-06 07:34

Consider the following XML:


    2
    
  

I need to deserialize this xml to an ob

2条回答
  •  爱一瞬间的悲伤
    2020-12-06 08:11

    To deserialize empty tags like 'c' in your example:

        
            2
            
        
    

    I used this approach. First it removes the null or empty elements from the XML file using LINQ and then it deserialize the new document without the null or empty tags to the Foo class.

        public static Foo ReadXML(string file)
        {
                Foo foo = null;
                XDocument xdoc = XDocument.Load(file);
                xdoc.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();
    
                XmlSerializer xmlSer = new XmlSerializer(typeof(Foo));
                using (var reader = xdoc.Root.CreateReader())
                {
                    foo = (Foo)xmlSer.Deserialize(reader);
                    reader.Close();
                }
                if (foo == null)
                    foo = new Foo();
    
                return foo;
        }
    

    Which will give you default values on the missing properties.

        foo.b = 2;
        foo.c = 0; //for example, if it's an integer
    

    I joined information from this links:

    Remove empty XML tags

    Use XDocument as the source for XmlSerializer.Deserialize?

提交回复
热议问题