Mohan Singh
Mohan Singh

Reputation: 1162

How to get the Line number where the xml tag is closed?

I am trying to get starting and ending line number of an XML tag(e.g.- employee in below XML code), I am able to get the starting line number of a tag in XML file but not the line number where the particular tag is closed.

Is there any way to get the line number where the tag is closed.

my XML code file.

<Employee>
      <Employee_Summary>
       <RID>1</RID>
       <Employee_ID> 78769</Employee_ID>
       <Name> Mohan Singh</Name>
      </Employee_Summary>
</Employee> 
<Employee>
      <Employee_Summary>
       <RID>2</RID>
       <Employee_ID> 78770</Employee_ID>
       <Name> Ramesh</Name>
      </Employee_Summary>
</Employee>

C# Code

foreach (var employee in employees)
{
 // code to get employee tag start Line number
 var elemntStartLine = ((IXmlLineInfo)employee).LineNumber;
 // here is want to get tag end Line number from xml file.
}

Here employees is of type IEnumerable<XElement>

Upvotes: 0

Views: 638

Answers (2)

Mohan Singh
Mohan Singh

Reputation: 1162

I found a solution to get the the line number where employee xml tag is closing.

foreach (var employee in employees)
{
 // code to get employee tag start Line number
 var elemntStartLine = ((IXmlLineInfo)employee).LineNumber;
 // here i get tag end Line number from xml file.
 var elemntEndLine =GetXelementEndLineNo(employee);
}  

 

 public int GetXelementEndLineNo(XElement xElement)
       {
                int endLineNo = 0;
                xElement.RemoveAll();
                xElement.Add(string.Empty);
                using (XmlReader xmlReader = xElement.CreateReader())
                {
                    var lineInfo = ((IXmlLineInfo)xmlReader);
                    while (xmlReader.Read())
                    {
                        if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName.ToUpper() == "EMPLOYEE")
                        {
                            endLineNo = lineInfo.LineNumber;
                        }
                    }
                }
                return endLineNo;
       }

Upvotes: 0

dba
dba

Reputation: 1175

On deserialized data you don't have any relation to the file structure. The only chance you have to read the file as ascii and try to loop over the lines doing some custom checks (holding line number for opening tags,and look for their closing ones...).

But since XML is no necessary intended or even broke up into lines, this is a very unreliable approach. You may ask yourself, what do you need this information for in first place? Maybe you find another formulation of your use case.

Upvotes: 2

Related Questions