2013-08-22 76 views
1

XML:如何使用linq to xml解析下面的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中的所有记录?

+1

我相信你的意思是linq到xml – Jonesopolis

+5

如果你控制XML的结构,我会改变XML,因为它的结构不正确 –

回答

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(); 
+0

很好的使用Zip(假设XML总是有相同数量的shift_time和count元素。 –

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下运行收集的孩子,并获得相当容易的处理组。应该从这里直接前进。