C #: string information when parsing XML using XmlDocument

What are my options for parsing an XML file using an XmlDocument and still storing string data for error messages? (as an aside, is it possible to do the same with XML Deserialisation?)

Options seem to include:

+7
source share
2 answers

The only other parameter that I know of is XDocument.Load() , which overloads take LoadOptions.SetLineInfo . This will be consumed in much the same way as an XmlDocument .

Example

+8
source

(Extension of answer from @Andy's comment)

There is no built-in way to do this using XmlDocument (if you are using XDocument , you can use XDocument.Load() overload, which accepts LoadOptions.SetLineInfo - see this question ).

While there is no built-in way, you can use the PositionXmlDocument wrapper class here (from the SharpDevelop project):

https://github.com/icsharpcode/WpfDesigner/blob/5a994b0ff55b9e8f5c41c4573a4e970406ed2fcd/WpfDesign.XamlDom/Project/PositionXmlDocument.cs

To use it, you will need to use the Load overload, which accepts the XmlReader (other Load overloads will be sent to the regular XmlDocument class, which will not give you information about the line number). If you use the XmlDocument.Load overload, which takes a file name, you need to change your code as follows:

 using (var reader = new XmlTextReader(filename)) { var doc = new PositionXmlDocument(); doc.Load(reader); } 

Now you can send any XmlNode from this document to PositionXmlElement to retrieve the row and column numbers:

 var node = doc.ChildNodes[1]; var elem = (PositionXmlElement) node; Console.WriteLine("Line: {0}, Position: {1}", elem.LineNumber, elem.LinePosition); 
+5
source

All Articles