C#

Getting LineNumber(s) in your XLINQ

At work the other day I had to do some work with some Xml fragments, which I decided to do using XLinq.

 

Where I wanted to validate a certain fragment, and also get line numbers out of the fragment when it was deemed invalid. Say I had this XML

<?xmlversion="1.0" encoding="utf-8"?>
<Clients>
  <Client>
    <FirstName>Travis</FirstName>
    <LastName>Bickle</LastName>
  </Client>
  <Client>
    <FirstName>Franics</FirstName>
    <LastName>Bacon</LastName>
  </Client>
</Clients>

XLine actually supoprts line numbers by the way of the IXmlLineInfo Interface

So say you had some code like this which grabbed a XNode and wanted to use it’s line number

XText travis = (from x in xml.DescendantNodes().OfType<XText>()
                where x.Value == "Travis"
                select x).Single();

var lineInfo = (IXmlLineInfo)travis;
Console.WriteLine("{0} appears on line {1}", travis, lineInfo.LineNumber);

What I was finding though was that my line numbers were always coming out with 0 reported as the lineNumber. Turns out there is a easy win for this, it is to do with how I was initially loading the
XDocument. I was doing this

var xml = XDocument.Load(file);

Which is bad, and will not load the line numbers. You need to do this instead

var xml = XDocument.Load(file, LoadOptions.SetLineInfo);

For a much better write up on all of this, check out this old post by Charlie Calvert, its much better than my post, wish I had of found that one first

http://blogs.msdn.com/b/charlie/archive/2008/09/26/linq-farm-linq-to-xml-and-line-numbers.aspx

5 thoughts on “Getting LineNumber(s) in your XLINQ

  1. In your first code snippet, you use a variable “phobos” without it ever being declared or assigned. (You also declare and assign a variable named “travis”, which you never use, so I guess you did an incomplete rename)

Leave a comment