// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using System.Xml; namespace E { public class FilterReader : TextReader { private class FilterBuffer { private TextReader tr; private string faketag; private string startmarker; private string endmarker; private string line; private int ix; private bool active; private bool done; public FilterBuffer(TextReader tr, string faketag, string startmarker, string endmarker) { this.tr = tr; this.faketag = faketag; this.startmarker = startmarker; this.endmarker = endmarker; line = "<" + faketag + ">"; // fake start tag ix = 0; active = false; done = false; } private bool Fill() { if(ix < line.Length) return true; // more characters in current line if(done) return false; // already seen EOF // get a new valid line do { line = tr.ReadLine(); // if EOF do fake end tag if(line == null) { line = ""; ix = 0; done = true; return true; } // sort out garbage from valid XML if(active) { int endix = line.IndexOf(endmarker); if(endix >= 0) { line = line.Substring(0, endix + endmarker.Length); active = false; } } else { int startix = line.IndexOf(startmarker); if(startix >= 0) { line = line.Substring(startix); active = true; int endix = line.IndexOf(endmarker); if(endix >= 0) { line = line.Substring(0, endix + endmarker.Length); active = false; } } else { line = null; // will trigger new read } } } while(line == null || line.Length == 0); // we got a valid line ix = 0; return true; } public int Read() { if(!Fill()) return -1; int c = line[ix]; ix++; return c; } public string ReadLine() { if(!Fill()) return null; string s = line.Substring(ix); ix = line.Length; return s; } } private FilterBuffer buf; public FilterReader(TextReader real, string faketag, string startmarker, string endmarker) { this.buf = new FilterBuffer(real, faketag, startmarker, endmarker); } public override int Read() { return buf.Read(); } public override string ReadLine() { return buf.ReadLine(); } public override string ReadToEnd() { throw new Exception("ReadToEnd does not work"); } } public class Program { public static void Main(string[] args) { XmlReader xr = new XmlTextReader(new FilterReader(new StreamReader(@"C:\work\dirty.xml"), "fake", "", "")); while(xr.Read()) { Console.WriteLine("type={0} name={1} value={2}", xr.NodeType, xr.Name, xr.Value); } xr.Close(); } } }