gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:10:46 26 4
gpt4 key购买 nike

早上好,

我有一个继承自 List 的集合,它有一个公共(public)属性。 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>

最佳答案

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

    [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();
}
}
}

关于C# Xml 序列化 List<T> 具有 Xml 属性的后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3416426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com