SeyoS
SeyoS

Reputation: 681

How to get line number from an XmlElement or a XPathNavigator

I try to get the line number from an XmlNode (which is an XmlElement) but it cannot be cast as an IXmlLineInfo. So I tried with XPathNavigator but it doesn't work either.

How can I get its line number?

Upvotes: 3

Views: 5267

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

It works fine for me with XPathNavigator over an XPathDocument, the snippet

    XPathDocument doc = new XPathDocument("XMLFile1.xml");
    foreach (XPathNavigator element in doc.CreateNavigator().Select("//*"))
    {
        Console.WriteLine("Element {0} at line {1}.", element.Name, (IXmlLineInfo)element != null ? ((IXmlLineInfo)element).LineNumber : 0);
    }

for the file

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <foo>3</foo>
  <foo>4</foo>
</root> 

outputs

Element root at line 2.
Element foo at line 3.
Element foo at line 4.

I think for XmlDocument you would need to extend the DOM implementation. If you want to manipulate an XML document then these days in the .NET world I would use XDocument/XElement, there you can set load options to ensure you get an IXmlLineInfo, see http://msdn.microsoft.com/en-us/library/bb538371%28v=vs.110%29.aspx and http://msdn.microsoft.com/en-us/library/system.xml.linq.loadoptions%28v=vs.110%29.aspx.

Upvotes: 7

Related Questions