使用不同格式时无法反序列化xml

问题描述 投票:0回答:1

我想将配置文件反序列化为这些类:

[Serializable()]
[XmlRoot("Configuration")]
public class Configuration
{
    [XmlArray("Persons")]
    [XmlArrayItem("Person", typeof(Person))]
    public List<Person> Persons { get; set; }
}

[Serializable()]
public class Person
{
    [XmlElement("Name")]
    public string Name { get; set; }
}

我可以这样做:

static Configuration LoadConfiguration(string path)
{
    var serializer = new XmlSerializer(typeof(Configuration));

    using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate))
    {
        return (Configuration)serializer.Deserialize(stream);
    }
}

Everythink 在

xml
文件结构如下时工作:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
    <Persons>
        <Person>
            <Name>foo</Name>
        </Person>
        <Person>
            <Name>bar</Name>
        </Person>
    </Persons>
</Configuration>

但它不适用于此结构:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
    <Persons>
        <Person Name ="foo" />
        <Person Name ="bar" />
    </Persons>
</Configuration>

当我尝试这个

xml
文件时,
Name
属性变为
null
。为什么?

c#
1个回答
0
投票

您必须使用

XmlAttribute

[Serializable()]
public class Person
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.