'How to access 'row' and 'column' of nodes when parsing XML

In C#, is there a way to work out an XmlNode's position in the original XML 'text', when the document is loaded from a file or string? I want to be able to report problems with an XML document that I am processing.

e.g:

"Error in foo.xml - value of attribute 'pet' must be a species of fluffy mammal, at line 27, column 13 [snippet of original XML text here...]"

Edit: The checks can't be done using schema validation. Here is another, less frivolous sample error message to illustrate: "specified addin type 'Addins.LogWindow' must be public"



Solution 1:[1]

Well you're not supposed to write your own XmlParser but in the Compact Framework we have no choice as XmlDocument is as slow as the Dalai Lama on ketamine so we use an XmlReader when parsing an Xml file.

We throw an exception whenever we find something messed up or inconsistent and we pass the XmlReader to the exception. We then can extract the line position by casting the XmlReader into a IXmlLineInfo object which contains properties for the line and position.

Don't know if this will help. Generally I wouldn't be writing my own XmlParser on desktop which is why im reticent to suggest this as a solution.

Solution 2:[2]

Would a XML Schema work for you?

http://support.microsoft.com/kb/318504

Solution 3:[3]

Sorry, there are very few DOM implementations that will remember the original parsed location of a Node for you. Most only report any position information on a parsing error. For example in DOM Level 3 LS you only get a reference to a DOMLocator when there is a DOMError.

The only imp I know of that keeps track after parsing is pxdom, and that's for Python so not of much use to you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sergio
Solution 3 bobince