使用 XmlSerializer 重命名平面 xml 数组中的数组项

发布于 2024-10-07 04:06:32 字数 910 浏览 0 评论 0原文

我有一个具有以下格式的 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 技术交流群。

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

发布评论

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

评论(2

冷月断魂刀 2024-10-14 04:06:32

使用包含数组的包装类,这将允许您应用 XmlElement 属性:

public class MyClassList
{
    [XmlElement("Item")]
    public MyClass[] Items { get; set; }
}

var items = new[]
{
    new MyClass { Property1 = "A", Property2 = "B" },
    new MyClass { Property1 = "C", Property2 = "D" },
};
var list = new MyClassList { Items = items };

using (var writer = new StringWriter())
{
    var xs = new XmlSerializer(typeof(MyClassList), new XmlRootAttribute("Items"));
    xs.Serialize(writer, list);
    writer.ToString().Dump();
}

Use a wrapper class that contains the array, this will allow you to apply the XmlElement attribute:

public class MyClassList
{
    [XmlElement("Item")]
    public MyClass[] Items { get; set; }
}

var items = new[]
{
    new MyClass { Property1 = "A", Property2 = "B" },
    new MyClass { Property1 = "C", Property2 = "D" },
};
var list = new MyClassList { Items = items };

using (var writer = new StringWriter())
{
    var xs = new XmlSerializer(typeof(MyClassList), new XmlRootAttribute("Items"));
    xs.Serialize(writer, list);
    writer.ToString().Dump();
}
向日葵 2024-10-14 04:06:32

就我个人而言,我会手动序列化和反序列化 - 我发现以这种方式更容易获得您想要的灵活性,而不是花很长时间搞乱内置序列化并忍受它施加的各种限制。 LINQ to XML 使其变得非常简单。例如,在这种情况下:

XDocument doc = XDocument.Load("test.xml");
// You could use an array if you really wanted, of course.
List<MyClass> list = doc.Root
                        .Elements("Item")
                        .Select(x => new MyClass {
                            Property1 = (string) x.Attribute("Property1"),
                            Property2 = (string) x.Attribute("Property2"),
                         })
                        .ToList();

诚然,如果您需要序列化具有复杂关系的对象(两个对象引用同一个子对象或其他对象),这会变得很麻烦,但我过去在这方面取得了很大的成功。

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:

XDocument doc = XDocument.Load("test.xml");
// You could use an array if you really wanted, of course.
List<MyClass> list = doc.Root
                        .Elements("Item")
                        .Select(x => new MyClass {
                            Property1 = (string) x.Attribute("Property1"),
                            Property2 = (string) x.Attribute("Property2"),
                         })
                        .ToList();

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.

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