Ricardo Felgueiras
Ricardo Felgueiras

Reputation: 3719

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...

Upvotes: 7

Views: 5158

Answers (4)

jlp
jlp

Reputation: 10358

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));
}

Upvotes: 3

funkymushroom
funkymushroom

Reputation: 2139

Take a look at Schematron. Its great for validation of this kind. While you CAN validate using Schema, Schematron just uses XSL and results in an XML document that has validation messages that you can make user friendly.

Upvotes: 0

Oded
Oded

Reputation: 498924

Validation errors normally come up as XmlSchemaException - you can catch these and use the Message property to report these to the user.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499880

Are you able to use .NET 3.5? If so, you can use the Validate extension method on XDocument and provide a ValidationEventHandler. When validation fails your handler will be called with a ValidationEventArgs which you can use to find the location of the error.

Upvotes: 2

Related Questions