简体   繁体   English

C#中的传统XMLElement

[英]Condtional XMLElement in c#

I am trying to serialize to XML using the following class file 我正在尝试使用以下类文件序列化为XML

public class BatchFile
{
    [XmlElement("File1")]
    public List<string> FileObject { get; set; }
}

Following is my C# code to serialize this class 以下是我的C#代码以序列化此类

 var batchFile = new BatchFile();
 XmlSerializer serializer = new XmlSerializer(typeof(BatchFile));
 using (TextWriter writer = new StreamWriter(@"E:\BatchFile1.xml"))
  {               
  serializer.Serialize(writer, batchFile);
  }

I need to use the XMLElement on FileObject property dynamically. 我需要动态使用FileObject属性上的XMLElement。

It will be File1 or File2 or File3. 这将是File1或File2或File3。

I am not sure how to proceed on this. 我不确定如何进行此操作。

Have referred How do I model a dynamic XML element in a C# serialization class? 已经提到了如何在C#序列化类中为动态XML元素建模? and Change xml element value dynamically 动态更改xml元素值

But they dont seem to work for me. 但是他们似乎没有为我工作。

First of all - I don't believe you're using the right tool for the job. 首先-我不认为您在使用正确的工具来完成这项工作。 XML serialization is a tool that allows you to convert an object into an easily transported (and human-readable) form - and back. XML序列化是一种工具,它允许您将对象转换为易于传输(并且易于阅读)的形式-并返回。 This does imply a fixed schema. 这确实意味着一个固定的模式。

If you insist on doing it using XML serialization, why not do the simplest approach? 如果您坚持使用XML序列化来实现,那么为什么不采用最简单的方法呢?

[XmlElement("File1")]
public List<string> File1 { get; set; }

[XmlElement("File2")]
public List<string> File2 { get; set; }

[XmlElement("File3")]
public List<string> File3 { get; set; }

[XmlIgnore]
public List<string> FileObject
{
   get { return this.File1 ?? this.File2 ?? this.File3; }
}

If you want nodes named File1 through FileN you're going to have to implement IXmlSerializable and build/parse the XML manually. 如果你想命名节点File1通过FileN你将不得不实行IXmlSerializable ,并建立/手动解析XML。 There are no attributes that will enumerate collection items and give then sequential names. 没有可以枚举集合项然后给出顺序名称的属性。

If you only support a finite number of elements (say 3), you could add properties for those 3 elements: 如果仅支持有限数量的元素(例如3),则可以为这3个元素添加属性:

public class BatchFile
{
    [XmlIgnore]
    public List<string> FileObject { get; set; }

    public string File1 
    { 
        get {return FileObject[0];} 
        set {FileObject[0] = value; }
    }

    public string File2 { get; set; }
    { 
        get {return FileObject[1];} 
        set {FileObject[1] = value; }
    }

    public string File3 { get; set; }
    { 
        get {return FileObject[2];} 
        set {FileObject[2] = value; }
    }

}

You'll need to add appropriate bounds checking, of course. 当然,您需要添加适当的边界检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM