XML反序列化为对象

时间:2017-12-07 10:46:46

标签: c# xml serialization

您好, 我想将XML反序列化(不太常见)。普通XML应该如下所示:

<library>
<books>
 <book name="1"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
</books>
</library>

正如你所看到的,里面有“书籍”分支,里面有一些“书”元素。没关系,很容易反序列化等等。但是我的XML看起来与众不同。在“书籍”里面有随机名称的元素。而不是'book'元素,而是具有书名本身的元素(作为元素名称)。这些元素中的内容总是有相同的元素,如“作者”和“细节”。

请看一下:

<library>
<books>
 <1><author></author><details></details></1>
 <2><author></author><details></details></2>
 <3><author></author><details></details></3>
</books>
</library>

有关如何从第二个XML创建对象的任何建议吗?

2 个答案:

答案 0 :(得分:1)

使用xml linq。我更改了xml所以tagsw 1,2,3是a,b,c,因为标签不能以数字开头

meta.dispatch({
  type: '@@redux-form/CHANGE',
  payload: null,
  meta: { ...meta, field: name },
})

答案 1 :(得分:0)

XmlSerializer会讨厌它 - 它用于修复元素的情况。选项:

  • 完全重写xml并使用XmlSerializer
  • 使用手动反序列化(like @jdweng's answer
  • 重写内存中的xml,并使用XmlSerializer

有关第三种选择的示例:

using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

static class P
{
    static void Main()
    {
        var xml = @"<library>
<books>
 <a><author>x</author><details>1</details></a>
 <b><author>y</author><details>2</details></b>
 <c><author>z</author><details>3</details></c>
</books>
</library>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var ser = new XmlSerializer(typeof(Book));

        List<Book> books = new List<Book>();
        foreach (XmlElement book in doc.SelectNodes("/library/books/*"))
        {
            var el = doc.CreateElement("book");
            el.SetAttribute("name", book.Name);
            foreach (XmlNode child in book.ChildNodes)
            {
                el.AppendChild(child.Clone());
            }

            using (var reader = new XmlNodeReader(el))
            {
                books.Add((Book)ser.Deserialize(reader));
            }
        }

        foreach(var book in books)
        {
            System.Console.WriteLine(book);
        }

    }
}
[XmlRoot("book")]
public class Book
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("author")]
    public string Author { get; set; }
    [XmlElement("details")]
    public string Details { get; set; }

    public override string ToString() => $"{Name} by {Author}: {Details}";
}

输出:

a by x: 1
b by y: 2
c by z: 3
相关问题