What I need to do?
I need to validate an XML file (pass the file path/location) against the XSD file (pass the file path/location). I need to check that it is wellformed no illegal characters and it has all the tags defined in the XSD i.e no tag missing. It matches the datatypes defined in the xsd. After that is done I need to parse the xml file to get the data and store it in database.
Questions?
1) Using XmlReaderSetttings with XmlDocument and XmlReader with Validate method will that help me acheive what I need? CAn any one help me with sampel code?
2) What is the best way to parse an xml file to get specific tags?
I am new to VB.net so any sample code help will be appreciated. Thanks!
Best Answer
Yes, you are on the right track. Validating an XML document can be done using either
XmlDocument
orXmlReader
(as I'll describe later, you can also useXDocument
). Which one you choose will depend on your situation, but they both work similarly. When they find an error with the document, they call aValidationEventHandler
delegate. TheXmlReader
calls it via an event in theXmlReaderSettings
object whereas theXmlDocument
calls it via a delegate passed as a parameter to itsValidate
method. Here is a simple class which can be used to collect the errors:The
ValidationEventHandler
method in that class matches the signature of theValidationEventHandler
delegate, so you can use it to collect the errors from either theXmlReader
or theXmlDocument
. Here's how you could use it with theXmlDocument
:And here's how you could use it with the
XmlReader
:Alternatively, you can also use the newer
XDocument
class. The way to do it withXDocument
is very similar toXmlDocument
. There is aValidate
extension method for theXDocument
which takes, yet again, aValidationEventHandler
delegate. Here's an example of that:As for loading the data from the XML document into a database, it's impossible to say how, precisely, to do that without knowing the schema of the XML document, the schema of the database, the kind of database, etc. I would recommend doing some research both into reading XML data and writing data to databases and see how far you get. If you have any specific questions when you run into trouble, we'll be here to help :)