Skip to main content
 首页 » 编程设计

c#之如何使用属性标记 C# 类以使其可序列化为 XML

2024年02月13日14oomusou

所以我要上课。我想让它可序列化(转换为 XML 并返回)。我知道如何使用 Xml.Linq 进行序列化..但它是手动序列化 - 不像 protobuf 那样自动序列化其 [ProtoContract] and other attributes当我标记类并将其返回和转发可序列化时。

所以我想知道我在挥手

public class Entries { 
    public List<Entry> Entries {get; set;} 
} 
 
public class Entry { 
    public string Id {get; set;} 
    public string Path {get; set;} 
} 

像这样获取 XML:

<entries> 
    <entry id="value" path="value"/> 
</entries> 

那么如何用属性标记 C# 类使其 XML 可序列化呢?

请您参考如下方法:

为此,您需要使用 [XmlRoot] 和 [XmlAttribute] 等属性。您可以将 XML 元素名称指定为属性的参数。

参见 http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx以及您可以使用的属性的 namespace 中的其余属性。