0

我有一个作为变量包含在其他类中的类,需要与其他类一起序列化为 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();

我知道我可以将 Class 更改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在每个想要将其用作属性而不是元素的类中添加 。我希望有一种方法可以在我想要的时候设置一个转换器,或者甚至将代码添加到 Class Bfor asAttributeand asElement

4

1 回答 1

0

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

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

于 2013-01-15T22:34:54.703 回答