1

How to validate data from .xml file with .xsd file using C# and replace invalid data with null value?

2 Answers 2

1

Look at the XmlSchemaValidator class. While it's not easy to use, it is very powerful.

It works via a "push" model. The API informs you what kind of XML would be valid at the current point in the validation. You then supply a valid piece of XML (element, attribute, etc), and ask again, what would be valid now. I have used this to create sample XML that conforms to a set of schemas.

Although I haven't tried it, I suppose you could feed your input XML to the validator, then pass some "empty" XML once you reach an invalid point in the parse.

2
  • If I'm not mistaken, this class can't be used in Silverlight. I wanted to use it once in an SL application but couldn't. Any alternative that works with Silverlight? By that time I just gave up code validation of XML files.
    – Guillaume
    Aug 21, 2012 at 4:34
  • It's quite obscure, so I doubt it's available for Silverlight. Only way I could see to use it would be to use it in a WCF service and call it from SL. Aug 21, 2012 at 5:16
-1

In .NET 3.5 to validate just use the following code

    public bool Validate(XmlReader xmlInput, XmlReader schemaDocument)
    {
        var xmlSchemaSet = new XmlSchemaSet();
        xmlSchemaSet.Add("", schemaDocument);
        try
        {
            var doc = XDocument.Load(xmlInput);
            bool valid = true;
            doc.Validate(xmlSchemaSet, (o, e) =>
            {
                valid = false;
            });
            return valid;
        }
        catch (Exception e)
        {
            return false;
        }
    }

but to correct your document, you should use XmlReader's methods and custom verification, I consider.

1
  • This doesn't actually answer the question. Aug 21, 2012 at 3:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.