简体   繁体   中英

Controlling XmlSerializer for Class depending on if it is an Attribute of XMLElement

I have a class that is included in other classes as a variable, and needs to be serialized along with the other classes as XML. In some classes it will be included as an attribute, and the rest it will be an element. Is there an easy way to handle this using XMLSerializer .

For the sake of making this clearer here is an example. I have Class B :

public class B {

    public string name { get; set; }

    public string description { get; set; }

    public B() { }

    public B(string name, string description) {
        this.name = name;
        this.description = description;
    }
}

Then Class A :

public class A {
    [XmlAttribute("aName")]
    public string name { get; set; }

    [XmlAttribute("bName")]
    public B b { get; set; }

    public A() { }

    public A (string name, B b){
        this.name = name;
        this.b = b;
    }                
}

Then to serialize it I do:

XmlSerializer serializer = new XmlSerializer(typeof(A));
TextWriter textWriter = new StreamWriter(@"C:\Test.xml");
serializer.Serialize(textWriter, new A("A Name", new B("B Name", "B Description")));
textWriter.Close();

I know I could change Class A to:

public class A {
    [XmlAttribute("aName")]
    public string name { get; set; }

    [XmlIgnore]
    public B b { get; set; }

    [XmlAttribute("bName")]
    public string bXml {get{return b==null ? null : b.name;} set{this.b = new B(value, null);}}

    public A() { }

    public A (string name, B b){
        this.name = name;
        this.b = b;
    }                
}

But since this happens in multiple locations, it would be nice to not have to add the bXML in every class that wants to use it as an attribute instead of as an element. I was hoping there was a way to set a converter when I want to this, or even add code to Class B for asAttribute and asElement .

By implementing the IXmlSerializable you can have full control over the xml you generate upon serialization.

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

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