Does anyone know how I can get the current line number of an System.Xml.XmlReader? I am trying to record where in a file I find Xml elements.
Take advantage of the IXmlLineInfo
interface supported by an XmlReader
:
IXmlLineInfo xmlInfo = (IXmlLineInfo)reader;
int lineNumber = xmlInfo.LineNumber;
Expanding on the IXmlLineInfo
interface, the documentation for this is pretty bad; from doing a bit of digging, I can tell you the following:
1) System.Xml.XmlReader
is abstract, so you're never going to be dealing with an instance of this, as such, the fact that it doesn't implement IXmlLineInfo
isn't massively concerning (although, if it did, it would make everything just that little bit easier :) )
2) The System.Xml.IXmlLineInfo
interface provides two properties: LineNumber
and LinePosition
(which are the things we care about), plus a method: HasLineInfo()
which, according to the documentation, will let you know if an implementor can return the lineinfo.
3) Of the documented inheritors of System.Xml.XmlReader
, we have:
System.Xml.XmlDictionaryReader - abstract, used by WCF for serialization, no IXmlLineInfo
System.Xml.XmlNodeReader - used when reading a node, no IXmlLineInfo
System.Xml.XmlTextReader - used when reading a stream of data, has IXmlLineInfo
System.Xml.XmlValidatingReader - used when reading a stream of data and validating, has IXmlLineInfo.
Looking at the above list, the XmlDictionaryReader
is going to be used internally, the XmlNodeReader
is going to be used when you've passed in a node to be read (which, having been parsed, is already untethered from its source document), the XmlTextReader
and XmlValidtingReader
(both of which implement IXmlLineInfo
), are going to be used when you're reading from a document. So, the long and the short of it seems to be that if it's possible or useful to give you position information, the framework will do so.
That being said, the documentation seems to be very light. Having just done this, I ended up doing (with _xr being an unknown concrete implementation of System.Xml.XmlReader
):
string position = "(unknown)";
if (_xr != null && typeof(System.Xml.IXmlLineInfo).IsInstanceOfType(_xr) &&
((System.Xml.IXmlLineInfo)_xr).HasLineInfo())
{
System.Xml.IXmlLineInfo li = (System.Xml.IXmlLineInfo)_xr;
position = "(" + li.LineNumber.ToString() + "," + li.LinePosition.ToString() + ")";
}
With all of that being said, when I actually run the code above, the type of _xr ends up being System.Xml.XsdValidatingReader
(good luck finding documentation on that!), which inherits from System.Xml.XmlReader
, but doesn't inherit from System.Xml.XmlValidatingReader
or System.Xml.XmlTextReader
. As such, it's probably wise to use an approach like the above.
来源:https://stackoverflow.com/questions/621059/current-line-number-from-a-system-xml-xmlreader-c-net