如果有未识别的元素
目的是将XML-ArarayItems逐列到我的特定枚举中。
using System.Xml.Serialization;
public enum Example
{
[XmlEnum(Name = "Ex1")]
Ex1,
[XmlEnum(Name = "Ex2")]
Ex2
}
[XmlRoot(ElementName = "Schema", Namespace = "http://www.placeholder.com")]
public class Model
{
[XmlArrayItem("Example")
public List<Example> Examples;
}
只要我的XML中的每个元素名称与枚举值之一匹配,它的工作正常。 (应该是)
<?xml version="1.0" encoding="UTF-8"?>
<Schema xmlns="http://www.placeholder.com" version="1">
<Examples>
<Example>Ex1</Example>
<Example>Ex2</Example>
<Example>Ex1</Example>
</Examples>
</Schema>
但是,我要做的是应将任何非匹配元素(例如:'ex3')化为某种集体默认值。有适当的方法吗?
我尝试过的事情:
在我的模型中声明了“示例”
无效- 在我的模型
添加
[xmlenum(name =“”)] 未知
到枚举
编辑
private static TXmlClass ReadXml<TXmlClass>(String filename)
{
using (var reader = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var xmlSerializer = new XmlSerializer(typeof(TXmlClass));
return (TXmlClass)xmlSerializer.Deserialize(reader);
}
}
The goal is to deserialize xml-arrayitems into my specific enum.
using System.Xml.Serialization;
public enum Example
{
[XmlEnum(Name = "Ex1")]
Ex1,
[XmlEnum(Name = "Ex2")]
Ex2
}
[XmlRoot(ElementName = "Schema", Namespace = "http://www.placeholder.com")]
public class Model
{
[XmlArrayItem("Example")
public List<Example> Examples;
}
It works fine as long as every element name in my xml matches one of the enum values. (as it should be)
<?xml version="1.0" encoding="UTF-8"?>
<Schema xmlns="http://www.placeholder.com" version="1">
<Examples>
<Example>Ex1</Example>
<Example>Ex2</Example>
<Example>Ex1</Example>
</Examples>
</Schema>
However, what I want to do is deserializing any non-matching elements (e.g.: 'Ex3') into some kind of collective default value. Is there a proper way?
Things i tried:
declared 'Example' nullable in my model
added
[XmlEnum(Name = "")]
Unknownto the enum
Edit
private static TXmlClass ReadXml<TXmlClass>(String filename)
{
using (var reader = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var xmlSerializer = new XmlSerializer(typeof(TXmlClass));
return (TXmlClass)xmlSerializer.Deserialize(reader);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论