gpt4 book ai didi

C# XML Serializer 不会存储属性

转载 作者:太空狗 更新时间:2023-10-29 23:42:09 24 4
gpt4 key购买 nike

这是我在 Stack Overflow 上的第一个问题。如果我在学习这里的工作原理时没有做对,请提前道歉。

这是我的代码:

public void TestSerialize()
{
ShoppingBag _shoppingBag = new ShoppingBag();
Fruits _fruits = new Fruits();
_fruits.testAttribute = "foo";

Fruit[] fruit = new Fruit[2];
fruit[0] = new Fruit("pineapple");
fruit[1]= new Fruit("kiwi");

_fruits.AddRange(fruit);

_shoppingBag.Items = _fruits;

Serialize<ShoppingBag>(_shoppingBag, @"C:\temp\shopping.xml");
}

public static void Serialize<T>(T objectToSerialize, string filePath) where T : class
{
XmlSerializer serializer = new XmlSerializer(typeof(T));

using (StreamWriter writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, objectToSerialize);
}
}

[Serializable]
public class ShoppingBag
{
private Fruits _items;

public Fruits Items
{
get { return _items; }
set {_items = value; }
}
}

public class Fruits : List<Fruit>
{
public string testAttribute { get; set; }
}

[Serializable]
public class Fruit
{
public Fruit() { }

public Fruit(string value)
{
Name = value;
}

[XmlAttribute("name")]
public string Name { get; set; }
}

它生成这个 XML:

<?xml version="1.0" encoding="utf-8" ?> 
<ShoppingBag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Fruit name="pineapple" />
<Fruit name="kiwi" />
</Items>
</ShoppingBag>

我不明白为什么我没有收到 <Items testAttribute="foo">

谁能告诉我我需要在我的代码中添加什么,以便序列化程序将此属性写出?

谢谢,

最佳答案

你需要一个中间类:

class Program
{
static void Main()
{
var shoppingBag = new ShoppingBag
{
Items = new ShoppingBagItems
{
Fruits = new List<Fruit>(new[] {
new Fruit { Name = "pineapple" },
new Fruit { Name = "kiwi" },
}),
TestAttribute = "foo"
}
};
var serializer = new XmlSerializer(typeof(ShoppingBag));
serializer.Serialize(Console.Out, shoppingBag);
}
}

public class ShoppingBag
{
public ShoppingBagItems Items { get; set; }
}

public class ShoppingBagItems
{
[XmlElement("Fruit")]
public List<Fruit> Fruits { get; set; }

[XmlAttribute("testAttribute")]
public string TestAttribute { get; set; }
}

public class Fruit
{
[XmlAttribute("name")]
public string Name { get; set; }
}

另请注意,您不需要使用 [Serializable] 来装饰您的类属性,因为它仅用于二进制序列化。另一点是你不需要从 List<T> 派生。 ,只需将其用作属性即可。

关于C# XML Serializer 不会存储属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591985/

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