简体   繁体   中英

Condtional XMLElement in c#

I am trying to serialize to XML using the following class file

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

Following is my C# code to serialize this class

 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.

It will be File1 or File2 or 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? and Change xml element value dynamically

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. This does imply a fixed schema.

If you insist on doing it using XML serialization, why not do the simplest approach?

[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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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