XML DeSerialize - Possible to Trap Extra XML in File?

笑着哭i 提交于 2019-12-02 15:46:30

问题


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.



来源:https://stackoverflow.com/questions/23526898/xml-deserialize-possible-to-trap-extra-xml-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!