C#: Line information when parsing XML with XmlDocument
Asked Answered
W

2

7

What are my options for parsing an XML file with XmlDocument and still retain line information for error messages later on? (as an aside, is it possible to do the same thing with XML Deserialisation?)

Options seem to include:

Winola answered 12/4, 2011 at 0:13 Comment(0)
K
8

The only other option I know of is XDocument.Load(), whose overloads accept LoadOptions.SetLineInfo. This would be consumed in much the same way as an XmlDocument.

Example

Kass answered 12/4, 2011 at 1:5 Comment(3)
For current .net this would be great.. but unfortunately I'm still writing for .net 2.0 from the 80s. (I would have mentioned in the question but I didn't want to date the post)Winola
I thought that might be the case. Between the other two, I think I would prefer the XPathDocument approach.Kass
@Andy this should be an answer.. it works well if you're stuck with old C#.Abdella
L
7

(Expanding answer from @Andy's comment)

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

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

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

In order to use it, you will need to use the Load overload that accepts an XmlReader (the other Load overloads will go to the regular XmlDocument class, which will not give you line number information). If you are currently using the XmlDocument.Load overload that accepts a filename, you will need to change your code as follows:

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

Now, you should be able to cast any XmlNode from this document to a PositionXmlElement to retrieve line number and column:

var node = doc.ChildNodes[1];
var elem = (PositionXmlElement) node;
Console.WriteLine("Line: {0}, Position: {1}", elem.LineNumber, elem.LinePosition);
Lepido answered 10/11, 2015 at 2:57 Comment(1)
This is really good for adding retrospectivley - I had written lots of code based on XmlDocument, and simply by adding this file and then adding the 3 lines of code suggested I am able to have useful positional user feedback : ) ... you need to add using ICSharpCode.WpfDesign.XamlDom; - that's probably blindingly obvious to C# users, but I am new to C# :o ... +1!Trincomalee

© 2022 - 2024 — McMap. All rights reserved.