XMLを読み込む方法

文字列をXMLとして読み込む

sample[VB.net]

Sub Main()
  Dim contents As String =""
  contents &= "<?xml version=""1.0"" encoding=""UTF-8""?>"
  contents &= "<data>"
  contents &=   "<Writer sex=""men="">鈴木一郎"
  contents &=     "<book>XML入門</book>"
  contents &=     "<price>1200</price>"
  contents &=     "<Sales>"
  contents &=       "<store code=""001="">100</store>"
  contents &=       "<store code=""002="">150</store>"
  contents &=       "<store code=""003="">NoHand</store>"
  contents &=       "<store code=""004="">300</store>"
  contents &=     "</Sales>"
  contents &=   "</Writer>"
  contents &= "</data>"
  Dim doc As New XmlDocument
  Dim item As XmlElement
  doc.LoadXml(contents)
End Sub


読み込み時にスキーマ適合を確認する

XmlDocument使用時

Sub Main()
    Dim schemaPath As String = "Schema.xsd"
    Dim xmlfile As String = "targetFile.xml"
    Dim doc As XmlDocument = New XmlDocument
 
    '*a↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    Dim ValidatingReader As XmlValidatingReader = New XmlValidatingReader(New XmlTextReader(xmlFile))
    ValidatingReader.Schemas.Add(Nothing, schemaPath)
    ValidatingReader.ValidationType = ValidationType.Schema
    doc.Load(ValidatingReader)
 
 
    '*b↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    Dim SchemaSet As New XmlSchemaSet()
    SchemaSet.Add(Nothing, schemaPath)
    Dim settings As New XmlReaderSettings
    settings.ValidationType = ValidationType.Schema
    settings.Schemas = SchemaSet
 
    AddHandler settings.ValidationEventHandler, AddressOf CallBack
 
    Dim reader As XmlReader = XmlReader.Create(xmlFile, settings)
    Try
      doc.Load(reader)
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try
  End Sub
 
  Sub CallBack()
    Throw New System.Exception("There is a schema violation.")
  End Sub

.NET Framework 2.0 では、XmlValidatingReader クラスが廃止されています。それ以降は*aではなく*bの方法を使用してください。交互性により*aの方法でも問題なく作動はします。

AddHandler settings.ValidationEventHandler, AddressOf CallBackの部分で、読み込みに失敗したら"CallBack"という関数に処理をさせるようにしています。

CallBack 関数内ではエラーをスローさせています。必要に応じて処理を変更してください。


XDocument使用時

Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Linq

Sub main()
  Dim schemaPath As String = "Schema.xsd"
  Dim xmlfile As String = "targetFile.xml"
  Dim doc As XDocument
 
  Dim SchemaSet As New XmlSchemaSet()
  SchemaSet.Add(Nothing, schemaPath)
  Dim settings As New XmlReaderSettings
  settings.ValidationType = ValidationType.Schema
  settings.Schemas = SchemaSet
  AddHandler settings.ValidationEventHandler, AddressOf CallBack
 
  Dim reader As XmlReader = XmlReader.Create(xmlfile, settings)
  Try
   doc = XDocument.Load(reader)
  Catch ex As Exception
   MsgBox(ex.Message)
  End Try
  reader.Close()
End Sub
 
Sub CallBack()
  Throw New System.Exception("There is a schema violation.")
End Sub

XmlDocument使用時と基本的な流れに違いはありません。