同一流上的多个(顺序)XmlReader 实例
本文关键字:顺序 XmlReader 实例 | 更新日期: 2023-09-27 18:34:57
我的问题应该相对简单:
是否可以(以任何方式(按顺序为同一流创建多个 XmlReader 对象,而无需第一个读取器在释放流后将流推进到末尾?
示例代码(请注意,对 ReadElement 的第二次调用将失败,因为无论出于何种原因,第一个读取器都将流推进到最后(:
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();
}
}
如果这不可能用"纯.Net',是否有任何替代("轻量级"(XML解析器库可以支持这种行为?
1.凌乱的方式
如果您能够保存每个序列的长度,则可以执行以下操作:
int len, i = 0; //len is the length of the interval
byte[] buffer = new byte[0xff];
while (len --> 0)
buffer[i++] = stream.ReadByte (); //copies the interval
这会从 MemoryStream 中单独复制字节间隔,并将其保存到缓冲区中。然后,您只需通过将缓冲区分配给新的 MemoryStream 或字符串来使用它(请参阅 XMLCreate 重载(。
问题是第一次读取操作太贪婪了,占用了整个间隔。
2.原始方式
编写您的一个流以满足您的需求!