本文介绍了XML DeSerialize - 是否可以在文件中捕获额外的 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法将额外的 XML 标记捕获在您在课堂上没有预料到的文件中?例如:
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.
谢谢,斯科特
推荐答案
我相信你可以使用 XmlSerializer
的 UnknownAttribute
, UnknownElement
等事件以捕获此类情况.
I believe you can use XmlSerializer
's UnknownAttribute
, UnknownElement
, etc. events to trap such cases.
这篇关于XML DeSerialize - 是否可以在文件中捕获额外的 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!