我可以使用属性将引用的对象展平为XML吗?

时间:2012-02-20 17:26:04

标签: c# xml-serialization

如果我有以下内容:

public class A
{
   public B b {get;set;}
}

public class B
{
   public string Name {get;set;}
   public string Address {get;set;
}

我想要的是xml:

<A Name="some data" Address="address..." />

所以我试图将引用的对象展平为属性。

这是否可以使用XmlSerializer?

1 个答案:

答案 0 :(得分:1)

是的,您可以使用IXmlSerializable接口执行此操作:

[Serializable]
public class MyClass : IXmlSerializable
{
    public MySubClass SubClass { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartAttribute("Name");
        writer.WriteString(SubClass.Name);
        writer.WriteEndAttribute();
        writer.WriteStartAttribute("Phone");
        writer.WriteString(SubClass.Phone);
        writer.WriteEndAttribute();
    }
}

[Serializable]
public class MySubClass
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

然后像这样调用它

        var serializer = new XmlSerializer(typeof(MyClass));
        using (var writer = new StringWriter())
        {
            var myClass = new MyClass() {SubClass = new MySubClass() {Name = "Test", Phone = "1234"}};
            serializer.Serialize(writer, myClass);
            string xml = writer.ToString();
        }

这是xml结果:

<?xml version="1.0" encoding="utf-16"?>
<MyClass Name="Test" Phone="1234" />

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

或者你可以只指定@Morpheus命名的属性;)