使用 XmlSerializer 重命名平面 xml 数组中的数组项
我有一个具有以下格式的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item Property1="A" Property2="B" />
<Item Property1="C" Property2="D" />
</Items>
我需要使用 XmlSerializer 将
元素读取为类 MyClass
的对象。
public class MyCLass
{
[XmlAttribute]
public string Property1 { get; set; }
[XmlAttribute]
public string Property2 { get; set; }
}
目前,我有以下代码来读取文件:
XmlSerializer serializer =
new XmlSerializer(typeof(MyClass[]), new XmlRootAttribute(@"Items"));
MyClass[] list = (MyClass[])serializer.Deserialize(...);
由于元素名称
与类名称 MyCLass
不同,因此数组中的元素不会被反序列化根本不。如果我将 MyClass
重命名为 Item
,上面的代码就可以工作,但不幸的是,我不允许更改 XML 文件或类名称。
我该如何映射两者以便可以正确读取文件?
提前致谢!
I have an XML file with the following format:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item Property1="A" Property2="B" />
<Item Property1="C" Property2="D" />
</Items>
I need to read the <Item>
elements as objects of class MyClass
using an XmlSerializer.
public class MyCLass
{
[XmlAttribute]
public string Property1 { get; set; }
[XmlAttribute]
public string Property2 { get; set; }
}
Currently, I have the following code to read the file:
XmlSerializer serializer =
new XmlSerializer(typeof(MyClass[]), new XmlRootAttribute(@"Items"));
MyClass[] list = (MyClass[])serializer.Deserialize(...);
Since the element name <Item>
is different from the class name MyCLass
, the elements in the array are not deserialized at all. The above code works if I rename MyClass
to Item
, but unfortunately I am not allowed to change the XML file or the class names.
How do I go about mapping the two so that the file can be read correctly?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用包含数组的包装类,这将允许您应用
XmlElement
属性:Use a wrapper class that contains the array, this will allow you to apply the
XmlElement
attribute:就我个人而言,我会手动序列化和反序列化 - 我发现以这种方式更容易获得您想要的灵活性,而不是花很长时间搞乱内置序列化并忍受它施加的各种限制。 LINQ to XML 使其变得非常简单。例如,在这种情况下:
诚然,如果您需要序列化具有复杂关系的对象(两个对象引用同一个子对象或其他对象),这会变得很麻烦,但我过去在这方面取得了很大的成功。
Personally I would serialize and deserialize manually - I've found that it's easier to get whatever flexibility you want that way rather than spending a long time messing around with the built-in serialization and living with the various restrictions it imposes. LINQ to XML makes it pretty simple. For example, in this case:
Admittedly this will get hairy if you need to serialize objects with complicated relationships (two objects referring to the same child or whatever) but I've had a great deal of success with it in the past.