1

I have XML file like this

<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>

And I'm tring to read it using following codes

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

But it doesn't loop each 'Alarm' parent element. Only shows 2013-10-05 and 11:55 in message box. Can't figure out what's wrong here? Please help. I need to loop through all date and time elements.

1 Answer 1

1

Have you considered using Linq and System.Xml.Linq?

The code for that looks like this:

        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);
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.