How to validate XML file in C#2.0
I need h开发者_如何学JAVAelp on how to validate Xml file simply?
I googled and found some tutorial said about developer can validate XML file based on an exist XSD schema file.(as below snppet).
For my case, I don't have an Xsd file. What can I do? Must I generate an Xsd file with a tool like XSD.exe?
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("", "c:\mySchema.xsd");
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationError);
XmlReader reader = XmlReader.Create("", settings);
XPathDocument doc = new XPathDocument(reader);
XPathNavigator navigatore = doc.CreateNavigator();
Actually the validation what I need is a very simple usage. Just make sure all the xml listed items/inner sub-items are paired. I will open and write my XML, but my XML can't be written successfully for some reason some time. Then when I load my XML next time, my Application will throw exception. That's why I need validate my xml file before load it.
Appreciated for your comments and suggestions.
If you don't have an xsd you should create one. If you are trying to validate any specific structure this is your best option.
If you just want to make sure a document is made up of valid XML you could get away with not having one but if you care about the schema then you must create a schema definition.
You can write your own XSD or use any number of tools. My advice is to write your own. It's not hard and it's worth knowing how to do.
Here is a link to get you started: http://www.w3schools.com/schema/default.asp
精彩评论