XElement LineNumber information

OpticTygre

New member
Joined
Oct 22, 2008
Messages
4
Programming Experience
5-10
Hi,

I know that to get the line number that an element (XElement) starts at, I can use:

VB.NET:
CType(XElement, System.Xml.IXmlLineInfo).LineNumber

My question is, how can I get the line number of where the element end tag is located within the XDocument?

Thanks!

-Jason
 
After much trial and error, I have discovered some interesting behavior in LINQ XML objects.

The end result is that when you load an XDocument and provide the option to SetLineInfo, not all line information is captured. If you load a document using an XMLReader, and the StringReader overload, all line information is captured.

The XmlNode object that is returned when doing an XMLReader.Read function contains a NodeType enumeration, which defines the type of object the reader is currently associated with. This can be Element, CType, EndElement, Text, and others. It will also provide line information for each and every node that is detected. If you Loop through the Nodes or Elements contained within an XDocument or XElement, Line information is only given for the start element tag and the value data contained within, but not the end element.

The XNode object also contains a NodeType property, but, when enumerting through nodes of an element using:

VB.NET:
For Each Node in XElement.DescendantNodesAndSelf
   Debug.Writeline Node.NodeType.ToString
Next

You will notice that the XNodes contained in an XElement do not support the EndElement NodeType.

Interestingly, if you use an XMLReader to get all the line information, you must create that reader from the XML directly:

VB.NET:
Dim reader As XmlReader = XmlReader.Create(New IO.StringReader(Element.ToString), readerSettings, context)

If you create the XMLReader through an XElement, the line information is not captured correctly:

VB.NET:
Dim reader As XmlReader = XmlReader.Create(XElement.CreateReader, readerSettings)

These are the differences that I've seen between LINQ to XML and the normal System.XML objects. I'm not sure if this is actually a "bug" in the framework, but it seems to me that simple line number information should have been carried over to the LINQ objects as well.
 
Back
Top