XmlReader.ReadtoFollowing has state EndofFile why?
I've produced this code to read an xml file from a string, however it has problems. Notably the ReadToFollowing() method returns nothing. It seems to seek the whole xmlstring, then set the XMLReader state to the EndofFile. I'm very puzzled by this, ReadStartElement() works and the n开发者_如何学Goext element is read as "heading" as you'd expect.
Here's my code, my idea is to read through the xml pulling out the fields I require;
List<string> contentfields = new List<string>() { "heading", "shortblurb", "description" };
string xml = @"<filemeta filetype='Audio'><heading>Fatigue & Tiredness</heading><shortblurb>shortblurb</shortblurb><description /><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>";
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
reader.ReadStartElement("filemeta");
foreach (String field_str in contentfields)
{
reader.ReadToFollowing(field_str);
if (reader.Name.ToString() == field_str)
{
Console.WriteLine(field_str + " " + reader.ReadElementContentAsString());
}
}
}
Console.ReadKey();
That's because reader.ReadStartElement("filemeta");
will position the reader on the xml tag heading
.
ReadToFollowing will then do 1 read (reading past your heading
tag) and then start to seek an element with the name heading. As you just read past it, ReadToFollowing will not find it anymore and read to the end of the file.
If you want to avoid this, change your code like this :
List<string> contentfields = new List<string>() { "heading", "shortblurb", "description" };
string xml = @"<filemeta filetype='Audio'><heading>Fatigue & Tiredness</heading><shortblurb>shortblurb</shortblurb><description /><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>";
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
reader.ReadStartElement("filemeta");
foreach (String field_str in contentfields)
{
if (reader.Name.ToString() != field_str)
{
reader.ReadToFollowing(field_str);
}
//still keep this if because we could have reached the end of the xml document
if (reader.Name == field_str)
{
Console.WriteLine(field_str + " " + reader.ReadElementContentAsString());
}
}
}
Console.ReadKey();
精彩评论