C# Xml 序列化列表具有 Xml 属性的后代

发布于 2024-09-13 05:06:37 字数 1815 浏览 3 评论 0原文

早上好,大家好,

我有一个来自 List 的集合,并且具有公共财产。 Xml 序列化程序不获取我的财产。列表项序列化良好。我尝试过 XmlAttribute 属性但无济于事。你们有解决办法吗?

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var people = new PersonCollection
        {
            new Person { FirstName="Sue", Age=17 },
            new Person { FirstName="Joe", Age=21 }
        };
        people.FavoritePerson = "Sue";

        var x = new XmlSerializer(people.GetType());
        var b = new StringBuilder();
        var w = XmlTextWriter.Create(b, new XmlWriterSettings { NewLineChars = "\r\n", Indent = true });
        x.Serialize(w, people);
        var s = b.ToString();
    }
}

[XmlRoot(ElementName="People")]
public class PersonCollection : List<Person>
{
    //DOES NOT WORK! ARGHHH
    [XmlAttribute]
    public string FavoritePerson { get; set; }    
}

public class Person
{
    [XmlAttribute]
    public string FirstName { get; set; }
    [XmlAttribute]
    public int Age { get; set; }
}

我收到以下 xml

<?xml version="1.0" encoding="utf-16"?>
        <People xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <Person FirstName="Sue" Age="17" />
          <Person FirstName="Joe" Age="21" />
        </People>

我想得到这个

<?xml version="1.0" encoding="utf-16"?>
        <People FavoritePerson="Sue" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <Person FirstName="Sue" Age="17" />
          <Person FirstName="Joe" Age="21" />
        </People>

Morning Guys,

I have a collection that descends from List and has a public property. The Xml serializer does not pick up my proeprty. The list items serialize fine. I have tried the XmlAttribute attribute to no avail. Do you guys have a solution?

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var people = new PersonCollection
        {
            new Person { FirstName="Sue", Age=17 },
            new Person { FirstName="Joe", Age=21 }
        };
        people.FavoritePerson = "Sue";

        var x = new XmlSerializer(people.GetType());
        var b = new StringBuilder();
        var w = XmlTextWriter.Create(b, new XmlWriterSettings { NewLineChars = "\r\n", Indent = true });
        x.Serialize(w, people);
        var s = b.ToString();
    }
}

[XmlRoot(ElementName="People")]
public class PersonCollection : List<Person>
{
    //DOES NOT WORK! ARGHHH
    [XmlAttribute]
    public string FavoritePerson { get; set; }    
}

public class Person
{
    [XmlAttribute]
    public string FirstName { get; set; }
    [XmlAttribute]
    public int Age { get; set; }
}

I'm getting the following xml

<?xml version="1.0" encoding="utf-16"?>
        <People xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <Person FirstName="Sue" Age="17" />
          <Person FirstName="Joe" Age="21" />
        </People>

I would like to get this

<?xml version="1.0" encoding="utf-16"?>
        <People FavoritePerson="Sue" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <Person FirstName="Sue" Age="17" />
          <Person FirstName="Joe" Age="21" />
        </People>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拥抱影子 2024-09-20 05:06:37

我继续通过实现 IXmlSerialized 解决了这个问题。如果存在更简单的解决方案,请发布!

    [XmlRoot(ElementName="People")]
public class PersonCollection : List<Person>, IXmlSerializable
{
    //IT WORKS NOW!!! Too bad we have to implement IXmlSerializable
    [XmlAttribute]
    public string FavoritePerson { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader reader)
    {
        FavoritePerson = reader[0];            
        while (reader.Read())
        {
            if (reader.Name == "Person")
            {
                var p = new Person();
                p.FirstName = reader[0];
                p.Age = int.Parse( reader[1] ); 
                Add(p);
            }
        }
    }
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("FavoritePerson", FavoritePerson);
        foreach (var p in this)
        {
            writer.WriteStartElement("Person");
            writer.WriteAttributeString("FirstName", p.FirstName);
            writer.WriteAttributeString("Age", p.Age.ToString());
            writer.WriteEndElement();            
        }
    }
}

I went ahead and solved the problem by implementing IXmlSerializable. If a simpler solution exists, post it!

    [XmlRoot(ElementName="People")]
public class PersonCollection : List<Person>, IXmlSerializable
{
    //IT WORKS NOW!!! Too bad we have to implement IXmlSerializable
    [XmlAttribute]
    public string FavoritePerson { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader reader)
    {
        FavoritePerson = reader[0];            
        while (reader.Read())
        {
            if (reader.Name == "Person")
            {
                var p = new Person();
                p.FirstName = reader[0];
                p.Age = int.Parse( reader[1] ); 
                Add(p);
            }
        }
    }
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("FavoritePerson", FavoritePerson);
        foreach (var p in this)
        {
            writer.WriteStartElement("Person");
            writer.WriteAttributeString("FirstName", p.FirstName);
            writer.WriteAttributeString("Age", p.Age.ToString());
            writer.WriteEndElement();            
        }
    }
}
白况 2024-09-20 05:06:37

这不是问题的答案,但我想我会提出一个简化代码开发的建议。

PersonCollection 类添加一个新的 Add 方法,如下所示:

public class PersonCollection : List<Person>, IXmlSerializable
{
...
    public void Add(string firstName, int age)
    {
        this.Add(new Person(firstName, age));
    }
...
}

然后,通过执行此操作,您可以将集合初始值设定项语法简化为:

var people = new PersonCollection
{
    { "Sue", 17 },
    { "Joe", 21 }
};
people.FavoritePerson = "Sue";

This isn't an answer to the question, but I thought I'd make a suggestion to ease in code development.

Add a new Add method to the PersonCollection class as such:

public class PersonCollection : List<Person>, IXmlSerializable
{
...
    public void Add(string firstName, int age)
    {
        this.Add(new Person(firstName, age));
    }
...
}

Then, by doing this, you can simplify your collection initializer syntax to:

var people = new PersonCollection
{
    { "Sue", 17 },
    { "Joe", 21 }
};
people.FavoritePerson = "Sue";
⊕婉儿 2024-09-20 05:06:37

如果您不介意必须包装所有列表函数,那么您可以将列表嵌入为类的属性,而不是从它派生。

然后,您可以使用 XmlElement 属性强制将 xml 元素写为平面列表(而不是嵌套)。

If you don't mind having to wrap all of the list functions, then you can embed the list as a property of the class rather than deriving from it.

You'd then use the XmlElement attribute to force the xml elements to be written out as a flat list (rather than being nested).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文