如何反序列化 XML 元素的编号数组 [英] How to deserialize a numbered array of XML elements
问题描述
我需要反序列化以下 XML:
I need to deserialize the following XML:
<TIMEWINDOWS>
<NUMBER>10</NUMBER>
<NO0>
<FROM>22-11-2013 08:00:00</FROM>
<TO>22-11-2013 11:59:00</TO>
</NO0>
<NO1>
<FROM>22-11-2013 12:00:00</FROM>
<TO>22-11-2013 15:59:00</TO>
</NO1>
<NO2>
<FROM>23-11-2013 08:00:00</FROM>
<TO>23-11-2013 11:59:00</TO>
</NO2>
<NO3>
<FROM>23-11-2013 12:00:00</FROM>
<TO>23-11-2013 15:59:00</TO>
</NO3>
...
</TIMEWINDOWS>
我需要的输出是 TimeWindow
对象的集合(列表、数组等等),例如:
The output that I require is a collection (list, array, whatever) of TimeWindow
objects, for example:
public class TimeWindow
{
public string From { get; set; }
public string To { get; set; }
}
是否有处理 NO0
、NO1
、NO2
、... 元素的标准方法?我总是可以构建自己的解析器,但我更喜欢使用标准方法,例如 System.Xml.Serialization.XmlSerializer
.
Is there a standard way to handle the NO0
, NO1
, NO2
, ... elements?
I can always build my own parser, but I would much prefer to use a standard approach, such as System.Xml.Serialization.XmlSerializer
.
推荐答案
这种格式相当疯狂.不幸的是,这意味着您需要使用 XDocument
或 XmlDocument
手动解析 xml.让我们使用前者,因为它更容易:
The format of this is quite crazy. Unfortunately this means you will need to parse the xml manually with XDocument
or XmlDocument
. Lets use the former as it is easier:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Xmlarrayload
{
class Program
{
static void Main(string[] args)
{
var document = XDocument.Parse(@"<TIMEWINDOWS>
<NUMBER>4</NUMBER>
<NO0>
<FROM>22-11-2013 08:00:00</FROM>
<TO>22-11-2013 11:59:00</TO>
</NO0>
<NO1>
<FROM>22-11-2013 12:00:00</FROM>
<TO>22-11-2013 15:59:00</TO>
</NO1>
<NO2>
<FROM>23-11-2013 08:00:00</FROM>
<TO>23-11-2013 11:59:00</TO>
</NO2>
<NO3>
<FROM>23-11-2013 12:00:00</FROM>
<TO>23-11-2013 15:59:00</TO>
</NO3>
</TIMEWINDOWS>");
int number = int.Parse(document.Root.Element("NUMBER").Value);
TimeWindow[] windows = (TimeWindow[])Array.CreateInstance(typeof(TimeWindow), number);
for (int i = 0; i < number; i++)
{
var element = document.Root.Element(string.Format("NO{0}", i));
TimeWindow window = new TimeWindow
{
//it is extremely important to use the correct culture (invariant) to parse the dates.
To = DateTime.ParseExact(element.Element("TO").Value, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat),
From = DateTime.ParseExact(element.Element("FROM").Value, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)
};
windows[i] = window;
}
}
}
public class TimeWindow
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
}
这篇关于如何反序列化 XML 元素的编号数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!