XML DeSerialize - Possible to Trap Extra XML in Fi

2019-03-05 02:58发布

问题:

Is there a way to trap the extra XML tags in a file that you did not anticipate in your class? For Example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace XmlDeserializerTest
{
    class Program
    {
        static void Main(string[] args)
        {

            XmlSerializer deserializer = new XmlSerializer(typeof(PersonInfo));
            StreamReader reader = new StreamReader(@"C:\XML\Xml.xml");
            object obj = deserializer.Deserialize(reader);
            PersonInfo D = (PersonInfo) obj;
            Console.WriteLine(D.address.Age);
            reader.Close();
            Console.ReadLine();
        }

    }


    [XmlRoot("MyInfo")]
    public class PersonInfo
    {
        public string Name { get; set; }
        public string Type { get; set; }
        [XmlElement("Address")]
        public Loc address = new Loc();

    }
    public class Loc
    {
        public string Age { get; set; }
        public string Location { get; set; }

    }
// File used by this program:

//  <?xml version="1.0" encoding="utf-8"?>
//  <MyInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
//    <Address>
//        <Age>51</Age>
//        <Location>Tulsa</Location>
//        <State>Oklahoma</State>
//    </Address>
//    <Name>Scott</Name>
//    <Type>Programmer</Type>
//</MyInfo>

}

This does not produce an error, it just doesnt load the State information. It just ignores it. I was wondering if there was a way to Trap this or send the extra code to another class or something.

Thanks, Scott

回答1:

I believe you can use XmlSerializer's UnknownAttribute, UnknownElement, etc. events to trap such cases.