我有像这样的XML文件
<Alarms>
<Alarm>
<Date>2013-10-05</Date>
<Time>11:50</Time>
</Alarm>
<Alarm>
<Date>2013-10-05</Date>
<Time>11:55</Time>
</Alarm>
<Alarm>
<Date>2013-10-05</Date>
<Time>12:05</Time>
</Alarm>
<Alarm/>
</Alarms>
我想用以下代码阅读
XmlTextReader objXmlTextReader = new XmlTextReader("Alarms.xml");
while (objXmlTextReader.Read())
{
objXmlTextReader.ReadToFollowing("Date");
MessageBox.Show(objXmlTextReader.ReadElementContentAsString());
objXmlTextReader.ReadToFollowing("Time");
MessageBox.Show(objXmlTextReader.ReadElementContentAsString());
}
objXmlTextReader.Close();
但它不会循环每个'Alarm'父元素。仅在消息框中显示2013-10-05和11:55。想不通这里有什么问题?请帮忙。我需要遍历所有日期和时间元素。
答案 0 :(得分:1)
您是否考虑过使用Linq和System.Xml.Linq?
代码如下:
var xdoc = XDocument.Load("Alarms.xml");
foreach (var x in xdoc.Root.Elements("Alarm")) {
Console.WriteLine(x.ToString());
var date = x.Element("Date");
var time = x.Element("Time");
Console.WriteLine("Date = {0}", date == null ? "<empty>": date.Value);
Console.WriteLine("Time = {0}", time == null ? "<empty>": time.Value);
}