H. Senkaya
H. Senkaya

Reputation: 773

How to get XElement from XDocument by Line Number

Is it possible in C# to get XElement of XDocument by giving in the line number?

Ive got any test XML like:

<Student>
  <Name>Josphine</Name>
</Student>
<Student>
  <Name>Hendrick</Name>
</Student>

I want to give as Parameter any integer like 5. 5 would give me the Element <Name>Hendrick</Name> Is this possible in any way? Or do I Need to parse the whole XDocument by a Reader and check the line number every loop.

Upvotes: 2

Views: 1270

Answers (2)

Cylian
Cylian

Reputation: 11182

There is a another look-around, if your XML is well-formed and you want your job get done using XLinq only, then below code might help you:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(@"<Students>
                                                  <Student>
                                                    <Name>Josphine</Name>
                                                  </Student>
                                                  <Student>
                                                    <Name>Hendrick</Name>
                                                  </Student>
                                              </Students>", LoadOptions.SetLineInfo);

            IEnumerable<XElement> descendants = doc.Descendants();

            foreach (XElement ele in descendants)
            {
                string ln_num = (((IXmlLineInfo)ele).HasLineInfo() ? ((IXmlLineInfo)ele).LineNumber.ToString() : "");
                string ln_pos = (((IXmlLineInfo)ele).HasLineInfo() ? ((IXmlLineInfo)ele).LinePosition.ToString() : "");
                Console.WriteLine(string.Format("{0} ({1}): at line no. {2}, position {3}", ele.Name.ToString(), ele.Value.ToString(), ln_num.ToString(), ln_pos.ToString()));
            }

            Console.ReadKey();
        }
    }
}

Upvotes: 2

Markiian Benovskyi
Markiian Benovskyi

Reputation: 2161

You can read your file to string array

string[] lines = File.ReadAllLines("path/to/file");

And then get your line like lines[4].

Or you should better look at XPath as your XML document can change.

Take a look at these exaples and tutorials: XPath Examples, Selecting Nodes.

Upvotes: 2

Related Questions