根据类是否为XMLElement的属性来控制类的XmlSerializer

时间:2013-01-15 20:51:28

标签: c# .net xml-serialization

我有一个类作为变量包含在其他类中,需要与其他类一起序列化为XML。在某些类中,它将作为属性包含在内,其余的将作为元素包含在内。有没有一种简单的方法可以使用XMLSerializer来处理这个问题。

为了使这里更清楚,这是一个例子。我有班级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;
    }
}

然后上课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;
    }                
}

然后序列化我:

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();

我知道我可以将班级A更改为:

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;
    }                
}

但是因为这发生在多个位置,所以不必在每个想要将其用作属性而不是元素的类中添加bXML。我希望有一种方法可以在我想要的时候设置转换器,甚至可以为BasAttribute的类asElement添加代码。

1 个答案:

答案 0 :(得分:0)

通过实现IXmlSerializable,您可以完全控制在序列化时生成的xml。

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