Multiple (Sequential) XmlReader instances on same stream



My question should be relatively straight forward:


Is it (In any way) possible to create multiple XmlReader objects for the same stream in sequence, without the first reader advancing the stream to the end once it's disposed?


Sample code (Note that the second call to ReadElement will fail because the first reader advanced the stream to the end, for whatever reason):



private static void DoTest()
{
using (var stream = new MemoryStream())
{
WriteElement("Test", stream);
Console.WriteLine("Stream Length after first write: {0}", stream.Length);
WriteElement("Test2", stream);
Console.WriteLine("Stream Length after second write: {0}", stream.Length);
stream.Position = 0;
Console.WriteLine(ReadElement(stream));
Console.WriteLine("Position is now: {0}/{1}", stream.Position, stream.Length);
Console.WriteLine(ReadElement(stream)); // Note that this will fail due to the stream position now being at the end.
}
}

private static string ReadElement(Stream source)
{
string result;
using (var reader = XmlReader.Create(source, new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Fragment,
CloseInput = false
}))
{
reader.Read();
result = reader.Name;
reader.Read();
}
return result;
}

private static void WriteElement(string name, Stream target)
{
using (var writer = XmlWriter.Create(target, new XmlWriterSettings
{
ConformanceLevel = ConformanceLevel.Fragment,
WriteEndDocumentOnClose = false,
OmitXmlDeclaration = true,
}))
{
writer.WriteStartElement(name);
writer.WriteEndElement();
}
}


If this is not possible with 'pure .Net', are there any alternative ('Light') Xml parser libraries out there that would support this behaviour?


No comments:

Post a Comment