如果有未识别的元素

发布于 2025-01-28 10:55:49 字数 1307 浏览 2 评论 0原文

目的是将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 = "")]
    Unknown

    to 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文