Anuja
Anuja

Reputation: 59

How to get an XML node at a given line number

I have an xml string ,While de serializing this xml I got an error like 'There is an error in XML document (498, 31)' .How can I get the xml node at this position in c#,so that I can send it to user that there is an issue in this particular node.

using (TextReader reader = new StringReader(xml)) 
{ 
    try 
    { 
        tempClass = (T)new XmlSerializer(typeof(T)).Deserialize(reader); 
    } 
    catch (InvalidOperationException ex) 
    { 
        //Here we need to show the node in which the error occurred 
    } 
}

Here in catch I got the message like 'There is an error in XML document (498, 31)'.I want to throw a custom error message to the user that, 'in this particular 'node' there is an issue' Any help or ideas on the subject would be greatly appreciated.

Upvotes: 0

Views: 1233

Answers (1)

Zesty
Zesty

Reputation: 2991

You can't use XML functions (as the file isn't valid XML), so read it as text and send the user the offending line.

string[] xmlLines = File.ReadAllLines(path);    
int linesFrom = 5;
int exceptionLine = 10; //Your  line number
int startLine = exceptionLine - linesFrom - 1 > 0 ? exceptionLine - linesFrom - 1: 0;
int endLine = exceptionLine + linesFrom - 1 > xmlLines.Count - 1 ? exceptionLine + linesFrom  - 1: xmlLines.Count - 1;
StringBuilder sb = new StringBuilder();
for (int i = startLine ; i < endLine ; i++)
{
    sb.Append(xmlLines[i]);
}
return sb.ToString();

Upvotes: 4

Related Questions