VB.NET 根据 XSD 文件验证 XML 文件并通过 xml 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18467389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET validating XML file against XSD file and parsing through the xml
提问by user565992
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.
我需要做什么?我需要针对 XSD 文件(传递文件路径/位置)验证 XML 文件(传递文件路径/位置)。我需要检查它是否格式正确,没有非法字符,并且它具有 XSD 中定义的所有标签,即没有缺少标签。它与 xsd 中定义的数据类型相匹配。完成后,我需要解析 xml 文件以获取数据并将其存储在数据库中。
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?
问题?1) 将 XmlReaderSetttings 与 XmlDocument 和 XmlReader 与 Validate 方法一起使用会帮助我实现我所需要的吗?任何人都可以帮助我使用示例代码吗?
2) What is the best way to parse an xml file to get specific tags?
2)解析xml文件以获取特定标签的最佳方法是什么?
I am new to VB.net so any sample code help will be appreciated. Thanks!
我是 VB.net 的新手,因此将不胜感激任何示例代码帮助。谢谢!
回答by Steven Doggart
Yes, you are on the right track. Validating an XML document can be done using either XmlDocumentor XmlReader(as I'll describe later, you can also use XDocument). Which one you choose will depend on your situation, but they both work similarly. When they find an error with the document, they call a ValidationEventHandlerdelegate. The XmlReadercalls it via an event in the XmlReaderSettingsobject whereas the XmlDocumentcalls it via a delegate passed as a parameter to its Validatemethod. Here is a simple class which can be used to collect the errors:
是的,您走在正确的轨道上。可以使用XmlDocument或来验证 XML 文档XmlReader(我将在后面介绍,您也可以使用XDocument)。您选择哪一个取决于您的情况,但它们的工作方式相似。当他们发现文档有错误时,他们会调用一个ValidationEventHandler委托。在XmlReader通过在一个事件调用它XmlReaderSettings目的而XmlDocument通过作为参数传递给它的传递委托呼叫它Validate的方法。这是一个可用于收集错误的简单类:
Public Class XmlValidationErrorBuilder
Private _errors As New List(Of ValidationEventArgs)()
Public Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
If args.Severity = XmlSeverityType.Error Then
_errors.Add(args)
End If
End Sub
Public Function GetErrors() As String
If _errors.Count <> 0 Then
Dim builder As New StringBuilder()
builder.Append("The following ")
builder.Append(_errors.Count.ToString())
builder.AppendLine(" error(s) were found while validating the XML document against the XSD:")
For Each i As ValidationEventArgs In _errors
builder.Append("* ")
builder.AppendLine(i.Message)
Next
Return builder.ToString()
Else
Return Nothing
End If
End Sub
End Class
The ValidationEventHandlermethod in that class matches the signature of the ValidationEventHandlerdelegate, so you can use it to collect the errors from either the XmlReaderor the XmlDocument. Here's how you could use it with the XmlDocument:
将ValidationEventHandler在类方法的签名相匹配ValidationEventHandler的委托,所以你可以用它来无论从收集错误XmlReader或XmlDocument。以下是如何将它与 一起使用XmlDocument:
Public Function LoadValidatedXmlDocument(xmlFilePath As String, xsdFilePath As String) As XmlDocument
Dim doc As New XmlDocument()
doc.Load(xmlFilePath)
doc.Schemas.Add(Nothing, xsdFilePath)
Dim errorBuilder As New XmlValidationErrorBuilder()
doc.Validate(New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler))
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
Throw New Exception(errorsText)
End If
Return doc
End Function
And here's how you could use it with the XmlReader:
以下是如何将它与 一起使用XmlReader:
Public Sub LoadXml(xmlFilePath As String, xsdFilePath As String)
Dim settings As New XmlReaderSettings()
settings.Schemas.Add(Nothing, xsdFilePath)
settings.ValidationType = ValidationType.Schema
Dim errorBuilder As New XmlValidationErrorBuilder()
AddHandler settings.ValidationEventHandler, New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler)
Dim reader As XmlReader = XmlReader.Create(xmlFilePath, settings)
' Read the document...
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
' Handle the errors
End If
End Function
Alternatively, you can also use the newer XDocumentclass. The way to do it with XDocumentis very similar to XmlDocument. There is a Validateextension method for the XDocumentwhich takes, yet again, a ValidationEventHandlerdelegate. Here's an example of that:
或者,您也可以使用较新的XDocument类。做到这一点的方式XDocument是非常相似的XmlDocument。有一个Validate扩展方法,XDocument它同样需要一个ValidationEventHandler委托。这是一个例子:
Public Function LoadValidatedXDocument(xmlFilePath As String, xsdFilePath As String) As XDocument
Dim doc As XDocument = XDocument.Load(xmlFilePath)
Dim schemas As New XmlSchemaSet()
schemas.Add(Nothing, xsdFilePath)
Dim errorBuilder As New XmlValidationErrorBuilder()
doc.Validate(schemas, New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler))
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
Throw New Exception(errorsText)
End If
Return doc
End Function
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 :)
至于将 XML 文档中的数据加载到数据库中,在不知道 XML 文档的架构、数据库的架构、数据库的类型等的情况下,无法准确地说如何做到这一点。我建议您这样做一些关于读取 XML 数据和将数据写入数据库的研究,看看你能走多远。如果您在遇到问题时有任何具体问题,我们将随时为您提供帮助 :)

