views:

229

answers:

4

Hi people!

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

+2  A: 

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.

Jon Skeet
Yes. I'm able to use .NET 3.5. Could you give me an example please?
arpf
@arpf: Not at the moment, no - but it should be pretty self-explanatory. Give it a try, and if you have problems, edit your question with the code you've tried.
Jon Skeet
How con I read a XML document using the line number?
arpf
XML documents don't have line numbers; text files do. To display the line containing an error, you need to process the file (or stream) that contains the XML document, e.g. open the file and read through it a line at a time until you hit the line containing the error.
Robert Rossney
@Robert: ValidationEventArgs actually contains an XmlSchemaException which *may* contain the offending position as LineNumber/LinePosition properties... so there may well be no need to do it all by hand. Can't say I've tried it myself, but that would be the first place to look.
Jon Skeet
A: 

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

Oded
A: 

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.

funkymushroom
+1  A: 

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