1

XML:

<shift_details>
    <shift_time>10:00 to 10:30</shift_time>
    <count>0</count>
    <shift_time>10:30 to 11:00</shift_time>
    <count>0</count>
    <shift_time>11:00 to 11:30</shift_time>
    <count>0</count>
    <shift_time>11:30 to 12:00</shift_time>
    <count>0</count>
    <shift_time>12:00 to 12:30</shift_time>
    <count>0</count>
</shift_details>

代码:

var slots = from c in xmlResponse.Descendants("shift_details")
            select new TimeSlots
            {
                time = (string)c.Element("shift_time"),
                count = (string)c.Element("count"),
            };

上面的代码只返回一个槽项作为输出。但是我的 xml 包含太多记录。

如何读取上述xml中的所有记录?

4

2 回答 2

5

那是因为Element只返回给定名称的第一个元素。您应该考虑更改您的 XML 结构以将不同的插槽彼此分开,例如:

<shift_details>
    <shift>
        <shift_time>10:00 to 10:30</shift_time>
        <count>0</count>
    </shift>
    (...)
</shift_details>

然后像这样查询它:

var slots = from c in xmlResponse.Element("shift_details").Elements("shift")
            select new TimeSlots
            {
                time = (string)c.Element("shift_time"),
                count = (string)c.Element("count"),
            };

或者如果你不能更改 XML,你仍然可以查询它,但它会有点棘手:

var doc = XDocument.Load("Input.txt");
var details = doc.Root;

var times = details.Elements("shift_time");
var counts = details.Elements("count");

var slots = times.Zip(counts, (t, c) => new { time = (string)t, count = (string)c }).ToList();
于 2013-08-22T12:06:14.860 回答
0

另一方面,如果您无法更改 XML 的结构,则需要开始发挥创意(尽管我不推荐这样做)。在这种情况下,你可能会接受这样的事情(即使从长远来看不太容易维护),它需要一组元素并将它们分成块,每个块都包含唯一的元素:

public static class Extensions
{
    public static IEnumerable<IEnumerable<XElement>> Partition(this IEnumerable<XElement> elements)
    {
        var currentList = new List<XElement>();
        var tags = new HashSet<string>();

        foreach (var xElement in elements)
        {
            if (tags.Contains(xElement.Name.LocalName))
            {
                yield return currentList.ToArray();
                currentList.Clear();
                tags.Clear();
            }

            currentList.Add(xElement);
            tags.Add(xElement.Name.LocalName);
        }

        yield return currentList.ToArray();
    }
}

然后,您可以通过此运行 shift_details 下的子集合,并获得相当容易处理的组。从这里应该直截了当。

于 2013-08-22T12:35:02.327 回答