I had this code for reading XML file:
using (XmlReader reader = XmlReader.Create(path + "\\AddressBook\\settings.xml"))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
if (reader.Name == "Person")
{
Person p = new Person();
reader.Read();
reader.Read();
// Get name
p.name = reader.Value;
reader.Read(); // skip end tag of previous element
reader.Read(); // read start tag of email
reader.Read(); // read email value
// Get email
p.email = reader.Value;
reader.Read();
reader.Read();
reader.Read();
// Get first name
p.address = reader.Value;
reader.Read();
reader.Read();
reader.Read();
// Get notes
p.notes = reader.Value;
reader.Read();
reader.Read();
reader.Read();
// Get dob
p.dob = DateTime.Parse(reader.Value);
lPeople.Add(p);
}
}
}
}
Thing is it is working but failed on this XML element:
<Person>
<Name />
<Email />
<StreetAddress />
<Notes>note</Notes>
<DateOfBirth>5/20/2015 8:04:15 PM</DateOfBirth>
</Person>
It failed because you can see when I added empty elements as name, email and address no start and end tags where added (by XMLWriter
), rather just <Name/>
, hence my reading logic above failed by reading wrong elements. What is the workaround about this usually?
note: Answer from here using extension method doesn't work for me for some reasons, still no start and end tags are written for empty elements
update: The answer by Jon Hanna below is not working for me. What happens is if I have read some element say "Email" as soon as ReadElementContentAsString
is called, it seems it jumps on other element like "Notes". Btw this is link with the XML on which it fails J. Hanna's approach