Question

I have created a class in order to validate some XML. Within that class I have a validation method. I also have a .xsd file which contains my XML schema. I've been told that to use this file I must "Load the xsd file into a string"

How do you load an xsd file into a string?

Was it helpful?

Solution

It is quite easy to read the entire file into a string:

string schema;
using(StreamReader file = new StreamReader(path)
{
    schema = file.ReadToEnd();
}

Hope this helps you in your quest.

OTHER TIPS

Without more context, I have no idea what Load the xsd file into a string actually means, but there are far simpler methods to validate an XML.

var xDoc = XDocument.Load(xmlPath);
var set = new XmlSchemaSet();

using (var stream = new StreamReader(xsdPath))
{
    // the null here is a validation call back for the XSD itself, unless you 
    //  specifically want to handle XSD validation errors, I just pass a null and let 
    //  an exception get thrown as there usually isn't much you can do with an error in 
    //  the XSD itself
    set.Add(XmlSchema.Read(stream, null));                
}

xDoc.Validate(set, ValidationCallBack);

Then you just need a method called ValidationCallBack in your class to be your handler for any validation failures (you can name it whatever you want, but delegate parameter the Validate() method above has to reference this method):

public void ValidationCallBack(object sender, ValidationEventArgs e)
{
    // do something with any errors
}

you can try with this code

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add("....", "youXsd.xsd");
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(YourSettingsValidationEventHandler);

        XmlReader books = XmlReader.Create("YouFile.xml", settings);

        while (books.Read()) { }


       //Your validation
       static void YourSettingsValidationEventHandler(object sender, ValidationEventArgs e)
       {

       }

2 If you want just load you can use StreamReader and ReadToEnd

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top