`
ticojj
  • 浏览: 157704 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

VB6: Validate XML against XSD in Visual Basic

 
阅读更多

http://www.nonhostile.com/howto-validate-xml-xsd-in-vb6.asp

 

 

 

 

This code requires a project reference to Microsoft XML 4.0 available from Microsoft's Download Center

This is a very simple example to demostrate the validation of a fragment of XML.
We want a validate than a element called sampleRoot has an attribute called myAttribute that can have a value of either 'animal', 'vegatable' or 'mineral'.

Sample XSD
This XSD defines our schema. We have to give it a namespace, for this example we're using urn:sample
    <!-- two namespaces used, xsd schema and the one we're defining (targetNamespace) -->
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:n="urn:sample"
               targetNamespace="urn:sample">
       
      <!-- define root element -->
      <xs:element name="sampleRoot" type="n:sampleRootType"/>
     
      <!-- define a datatype: sampleRootType -->
      <xs:complexType name="sampleRootType">
        <xs:attribute name="myAttribute" type="n:AnimalVegMineral" use="optional"/>
      </xs:complexType>
     
      <!-- define a Animal/Veg/Mineral data type -->
      <xs:simpleType name="AnimalVegMineral">
        <xs:restriction base="xs:string">
          <xs:enumeration value="animal"/>
          <xs:enumeration value="vegatable"/>
          <xs:enumeration value="mineral"/>
        </xs:restriction>
      </xs:simpleType>

    </xs:schema>

Samples of XML that Reference Our Schema Definition
XML documents that should conform to this schema must declare their namespace. The following fragments conform to the bove schema definition:
    <x:sampleRoot xmlns:x="urn:sample" myAttribute="animal"/>
The following fragments do not.
    <x:sampleRoot xmlns:x="urn:sample" myAttribute="piano"/>
Visual Basic Code to Validate an XML File against an XSD File
This function accepts the paths of two datafiles. An XML Schema Definition and an XML file.

    Private Function Validate(ByVal strXMLPath As String, _
                              ByVal strXSDPath As String) As Boolean

        Dim objSchemas As MSXML2.XMLSchemaCache40
        Dim objXML As MSXML2.DOMDocument40
        Dim objXSD As MSXML2.DOMDocument40
        Dim strNamespace As String
        Dim objErr As MSXML2.IXMLDOMParseError
       
        ' load XSD as DOM to populate in Schema Cache
        Set objXSD = New MSXML2.DOMDocument40
        objXSD.async = False
        If Not objXSD.Load(strXSDPath) Then
            Err.Raise 1, "Validate", "Load XSD failed: " & objXSD.parseError.reason
        Else
            ' get namespace name from XSD targetNamespace attribute
            strNamespace = objXSD.documentElement.getAttribute("targetNamespace")
        End If
       
        ' populate schema cache
        Set objSchemas = New MSXML2.XMLSchemaCache40
        objSchemas.Add strNamespace, objXSD
       
        ' load XML file (without validation - that comes later)
        Set objXML = New MSXML2.DOMDocument40
        objXML.async = False
        objXML.validateOnParse = False
        objXML.resolveExternals = False
       
        ' load XML, without any validation
        If Not objXML.Load(strXMLPath) Then
            Err.Raise 1, "Validate", "Load XML failed: " & objXML.parseError.reason
        End If
       
        ' bind Schema Cache to DOM
        Set objXML.schemas = objSchemas
       
        ' does this XML measure up?
        Set objErr = objXML.Validate()
       
        ' any good?
        Validate = (objErr.errorCode = 0)
        If objErr.errorCode <> 0 Then
            Err.Raise 1, "Validate", objErr.reason
        End If

    End Function

The above function could easily be adapted to load XML and XSD from string variables as opposed to data files.

For situations where multiple XML validations are required, repeatedly populating and destroying the schema cache is clearly ineffecient and could be optimised.

Examples Calling this Function
    Validate App.Path & "\sc-valid-tjh.xml", App.Path & "\sc-tjh-min.xsd"
    Validate App.Path & "\sc-valid.xml", App.Path & "\sc-tjh-min.xsd"
<script type="text/javascript">// <![CDATA[ google_ad_client = "pub-0974635012543471"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text"; google_ad_channel =""; google_color_border = "DCDCDC"; google_color_bg = "F5F5F5"; google_color_link = "000080"; google_color_url = "008000"; google_color_text = "000000"; // ]]></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

468 comments, Visual Basic 6, Thursday, April 15, 2004 16:24


 

Timeline Navigation for Visual Basic 6 posts
VB6: Convert HTML into Searchable Text using Regular Expressions (made 3 weeks later)
VB6: Validate XML against XSD in Visual Basic (this post, made Thursday, April 15, 2004 16:24)
VB6: Read XML from a Visual Basic Resource and Return Root Element (made 52 minutes earlier)


 

Comments
Hi,

I have a question: I've tried implementing this code with MSXML6 (replacing the 40's with 60's) and I have the follwing problem,

if the XML file has the declaration:

<fb:pratiche xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.fbk.it/pratiche file:///w:/xml/xsd/pratiche/Master.xsd" xmlns:fb="http://www.fbk.it/pratiche">

it refuses to validate saying :
error 1072897500 - "The node is niether valid nor invalid because no DTD/Schema declaration was found"

however, if I remove the xsi namespace, it works perfectly.

Do you have any idea what might be causing this?

Posted by: nick brandwood on Monday, March 6, 2006 16:19

Posted by: zisco on Wednesday, January 3, 2007 15:57
how we can puts check on email address whter an email address is valid or invalid?

Posted by: syed on Tuesday, August 14, 2007 12:05
Hi,

This example is a good help. Thanks.

I only had the following problem :

' does this XML measure up?
Set objErr = objXML.Validate()

If objErr.errorCode <> 0 Then
' worked fine
Debug.Print "errorCode " & objErr.errorCode
Debug.Print "reason " & objErr.reason

' I didn't manage to get following information
Debug.Print "filepos " & objErr.filepos
Debug.Print "Line " & objErr.Line
Debug.Print "linepos " & objErr.linepos
Debug.Print "srcText " & objErr.srcText
Debug.Print "url " & objErr.url
end if


Then I tried following code :

objXML.async = False
objXML.validateOnParse = True
objXML.resolveExternals = True

If Not objXML.Load(strXMLPath) Then
' In this case I could get the information from every member
Debug.Print "errorCode " & objXML.parseError.errorCode
Debug.Print "reason " & objXML.parseError.reason
Debug.Print "filepos " & objXML.parseError.filepos
Debug.Print "Line " & objXML.parseError.Line
Debug.Print "linepos " & objXML.parseError.linepos
Debug.Print "srcText " & objXML.parseError.srcText
Debug.Print "url " & objXML.parseError.url
end if

I don't understand, why it is like that. But you might have an answer.


P.S : objXML.resolveExternals = True solves the problem with MSXML6



Posted by: odCaplan on Monday, September 3, 2007 08:17
I also use the dll file msxml6.dll but I get the error:
error 1072897500 - "The node is niether valid nor invalid because no DTD/Schema declaration was found"

The beginning of the xsd file looks like:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Tmp" targetNamespace="urn:Tmp.xsd" xmlns:mstns="urn:Tmp.xsd" xmlns="urn:Tmp.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">

Does anyone know what the problem is?

Posted by: Mark on Thursday, April 17, 2008 15:22
Hi,

I've used your VB code on a project I'm working on and it works perfectly. Thank you.
At the moment, if I validate an XML file with more than one error, the function returns a message detailing the error found.
Would it be possible to modify this code so that the validation process continues on after the first error is found and returns a message detailing all errors found?
e.g.
Error parsing '2008-13-07' as date datatype.
The element: '{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.01}IntrBkSttlmDt' has an invalid value according to its data type.
Error parsing '2360.0q' as decimal datatype.
The element: '{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.01}IntrBkSttlmAmt' has an invalid value according to its data type.

Thanks in advance.


Posted by: Shaymoh on Friday, June 6, 2008 13:34
Did anyone have a solution of detecting all errors in one shot?

Posted by: Mike on Wednesday, January 14, 2009 21:54
great post, thanks!

Posted by: Ken on Wednesday, February 25, 2009 16:54
I found some code that loads all errors into an Array.

http://forums.devx.com/archive/index.php/t-136153.html


Posted by: Chris on Friday, March 20, 2009 18:26
The url given by Chris is for VB.net code, not VB6 -I think.

Posted by: IsabelG on Wednesday, July 8, 2009 08:25
How can i load xml file into datagrid in vb6...Please help

Posted by: saurabh on Wednesday, August 12, 2009 07:12
Thanks. These codes work successfully. I need another help. Is it possible to write xml with vb6.0 with a specified schema? If possible, then how?
分享到:
评论

相关推荐

    C#验证xml是否满足xsd规则

    在IT行业中,XML(eXtensible Markup Language)是一种用于存储和传输数据的标记语言,而XSD(XML Schema Definition)则是用来定义XML文档结构和数据类型的规范。当我们需要确保XML文档符合特定的结构和约束时,就...

    How to validate XML documents against Schematron rules

    ### 如何验证XML文档符合Schematron规则 #### Schematron模式概述 Schematron是一种简单而强大的结构化模式语言,用于对XML文档中的模式进行断言。它几乎完全依赖于XPath查询模式来定义规则和检查。Schematron验证...

    XML验证器(XSD验证XML)

    3. 验证XML:使用XML文档对象的validate方法,传入XSD文档对象作为参数。 4. 处理验证结果:检查验证结果,如果返回值为真,说明XML文档有效;否则,遍历错误集合获取错误信息。 通过这样的验证器,开发者可以确保...

    通过xsd验证xml

    在Visual Studio 2005(VS2005)中,使用C++来实现XML文档与XSD模式的验证是一个常见的需求。VS2005提供了一套强大的XML工具和库,如MSXML和ATL(Active Template Library),这些工具可以帮助开发者方便地处理XML和...

    XSD使用dom4j校验XML

    在IT行业中,XML(eXtensible Markup Language)是一种用于数据交换的标准格式,而XSD(XML Schema Definition)则是用于定义XML文档结构和数据类型的规范。DOM4J是Java环境中一个强大、灵活的XML处理库,它提供了...

    使用 Visual Basic 访问数据

    6. **动态数据绑定**:Visual Basic引入了动态数据绑定功能,允许在运行时将数据源绑定到控件,增强了灵活性和适应性。 7. **显示数据的控件**:Visual Basic提供了一系列数据绑定控件,如DataList、DataCombo、...

    Visual Basic 6编程技术大全 中译本扫描版带书签 2/2

    Visual Basic 6编程技术大全 是非常详细和深入的Vb6学习教程,无论对初学者还是有经验的开发人员,都非常有帮助 第一部分基础篇1 第1章 VB6入门1 1.1 集成开发环境1 1.1.1 运行IDE1 1.1.2 选择工程类型1 1.1.3 IDE...

    Visual Basic 6编程技术大全 中译本扫描版带书签 1/2

    Visual Basic 6编程技术大全 是非常详细和深入的Vb6学习教程,无论对初学者还是有经验的开发人员,都非常有帮助 第一部分基础篇1 第1章 VB6入门1 1.1 集成开发环境1 1.1.1 运行IDE1 1.1.2 选择工程类型1 1.1.3 IDE...

    validatejs-meteor:validate.js库的流星包

    validate.js的流星包 库@version 0.9.0的流星程序包装器! 当前软件包版本:0.6.0 安装 AtmosphereJS meteor add awsp:validatejs 手动安装 克隆此存储库,将其添加到目录packages (如果尚未创建,请在您的应用...

    validate表单验证

    6. **异步验证**:对于需要服务器端验证的情况,可以使用`remote`规则。它会发送一个AJAX请求到指定的URL,根据返回值(`true`或`false`)决定是否通过验证。 7. **即时反馈**:`validate`插件能实时检测用户输入,...

    perl-Params-Validate-1.29-5.el8.ppc64le.rpm

    官方离线安装包,亲测可用

    node-xsd-schema-validator:NodeJS的架构(XSD)验证器

    XSD架构验证器 (XSD)模式验证器,使用执行实际验证。 先决条件 在后台,该实用程序使用Java进行实际验证。... validateXML ( xmlStr , 'resources/foo.xsd' , function ( err , result ) { if ( err ) {

    ValidateXml.exe

    验证xsd和xml文件的小工具,方便检索xml格式是否与xsd一致。

    go-xsd-validate:基于libxml2的go的Xsd验证

    该软件包的目标是将xsd文件预加载到内存中,并使用libxml2(快速)验证xml,例如xml服务端点或api路由器的后主体。 在撰写本文时,我在github上找到的类似软件包没有提供错误详细信息,或者卡在了负载下。 除了提供...

    vc++验证xml文件正确性的方法

    MSXML提供了IXMLDOMDocument接口,它包含了一个validate方法,可以用来验证XML文档是否符合指定的XSD模版。 以下是使用VC++和MSXML进行XML验证的基本步骤: 1. **加载XML文件**:使用IXMLDOMDocument的load方法...

    BarTender ActiveX接口开发文档 适用于 Visual Basic 6.0, VB.NET, C#.zip

    它提供了多种接口供开发者集成到自己的应用程序中,其中ActiveX接口是适用于Visual Basic 6.0、VB.NET和C#等编程语言的一个选项。本文将详细阐述如何利用BarTender的ActiveX接口进行开发。 1. **BarTender ActiveX...

    ruby,xml

    5. **XML Schema验证**:如果你有XML Schema(XSD),可以使用Nokogiri的`Nokogiri::XML::Schema`类来验证XML文档是否符合规范: ```ruby schema = Nokogiri::XML::Schema(File.read('your_xml_schema.xsd')) doc...

    validate

    javascript表单验证:validate.js

    XMLoper.rar

    VB(Visual Basic)是Microsoft开发的一种面向对象的编程语言,它允许开发者轻松地创建桌面应用程序。在VB中操作XML,可以通过.NET Framework提供的System.Xml命名空间中的类来实现。 本压缩包“XMLoper.rar”似乎...

    bcrypt库C/C++使用

    bcrypt库C/C++使用 ```cpp #include "bcrypt/... std::cout &lt;&lt; BCrypt::validatePassword(password,hash) &lt;&lt; std::endl; std::cout &lt;&lt; BCrypt::validatePassword("123456",hash) &lt;&lt; std::endl; return 0; } ```

Global site tag (gtag.js) - Google Analytics