Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presenting xml validation errors

I'm trying to do this: I have an XML file that I want to validate according to an XSD file. So far so god... What I have to do is present the all node where is the validation error.

For example I have this XML file :

<people>
   <name>Jonh</name>
   <tel>91991919199191919</tel>
</people>

When I validate this file, this will get an error in the tel node. And I want to present the name to the final user of my applicattion and what is wrong in the XML for that .

I'm triyng to do this in C#.NET.

Thanks for the help...

like image 244
Ricardo Felgueiras Avatar asked Dec 29 '09 13:12

Ricardo Felgueiras


1 Answers

This code validate XML file against XSD file and returns error with line number.

public static void ValidateXML(Stream stream)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.Schemas.Add("", "yourXSDPath");
    settings.ValidationType = ValidationType.Schema;
    XmlReader reader = XmlReader.Create(stream, settings);
    XmlDocument document = new XmlDocument();
    document.Load(reader);
    ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
    document.Validate(eventHandler);
    reader.Close();
}

static void ValidationEventHandler(object sender, ValidationEventArgs e)
{}

try
{
    ValidateXML(yourXMLStream);
}

catch (XmlSchemaValidationException ex)
{
    Console.WriteLine(String.Format("Line {0}, position {1}: {2}", ex.Message, ex.LineNumber, ex.LinePosition));
}
like image 140
jlp Avatar answered Nov 03 '22 00:11

jlp