getting the current position from an XmlReader

dmo picture dmo · Jan 29, 2010 · Viewed 10k times · Source

Is there a way to get the current position in the stream of the node under examination by the XmlReader?

I'd like to use the XmlReader to parse a document and save the position of certain elements so that I can seek to them later.

Addendum:

I'm getting Xaml generated by a WPF control. The Xaml should not change frequently. There are placeholders in the Xaml where I need to replace items, sometimes looping. I thought it might be easier to do in code rather than a transform (I might be wrong about this). My idea was to parse it to a simple data structure of what needs to be replace and where it is, then use a StringBuilder to produce the final output by copying chunks from the xaml string.

Answer

RollerKostr picture RollerKostr · Aug 26, 2015

As Jon Skeet says, XmlTextReader implements IXmlLineInfo but XmlTextReader was deprecated since .NET 2.0 and the question is about XmlReader only. I found this solution:

XmlReader xr = XmlReader.Create( // MSDN recommends to use Create() instead of ctor()
    new StringReader("<some><xml><string><data>"),
    someSettings // furthermore, can't set XmlSettings on XmlTextReader
);
IXmlLineInfo xli = (IXmlLineInfo)xr;

while (xr.Read())
{
    // ... some read actions ...

    // current position in StringReader can be accessed through
    int line = xli.LineNumber;
    int pos  = xli.LinePosition;
}

P.S. Tested for .NET Compact Framework 3.5, but should work for others too.