I got this scenario:
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == itemElementName)
{
XElement item = null;
try
{
item = XElement.ReadFrom(reader) as XElement;
}
catch (XmlException ex)
{
//log line number and stuff from XmlException class
}
}
}
In the above loop I'm transforming a certain node (itemElementName) into an XElement.
Some nodes will be good XML and will go into an XElement, however, some will not.
In the CATCH, I'd like to not only catch the standard XmlException stuff... I'd also like to catch an extract of the current Xml and a string.
However, if I do any kind of READ operation on the node before I pass it to the XElement, it moves the reader forward.
How can get a "snapshot" of the contents of the OuterXml of the reader without interfering with it's position?
Actually ReadSubtree will return a reader which "wraps" the original reader. So reading through the new one will end up advancing the original one as well. You must consider XmlReader as a forward only reader, it simply can't go back. As for your scenario, instead of trying to remember part of the XML you can ask the reader for the position in the input file. Just cast it to IXmlLineInfo interface, it has methods to return line and position. Using this you could remember some starting position (before the element in question) and then the end position of the error. And then read that part from the intput file as a plain text.