当前位置:编程学习 > C#/ASP.NET >>

紧急求助!如何用VB编程验证xml文件有效性

如题,我想验证一个XML文件是否有效,比如说想关节点名称是否对应,是否存在非法字符 --------------------编程问答-------------------- XmlValidatingReader Sample Code 
I had to work up a sample of the XmlValidatingReader for a coworker, so I though I'd share it with everyone.  Here is a quick example of using the XmlValidatingReader.  There are other ways to construct/use it, but this is the most common method around here.  Hope this helps someone.

using System;

using System.IO;

using System.Xml;

using System.Xml.Schema;

 

 

namespace ConsoleApplication1

{

      

      class Class1

      {

            

            [STAThread]

            static void Main(string[] args)

            {

                  // path's to xml/xsd

                  const string path = @"C:\Projects\PSLL\ConsoleApplication1";

                  const string xmlPath = path + @"\franchise_detail.xml";

                  const string xsdPath = path + @"\Program.xsd";

 

                  // Create a new validating reader

                  XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(xmlPath)));

                  

                  // Create a schema collection, add the xsd to it

                  XmlSchemaCollection schemaCollection = new XmlSchemaCollection();

                  schemaCollection.Add("http://detail.franchise.scarlett",xsdPath);

 

                  // Add the schema collection to the XmlValidatingReader

                  reader.Schemas.Add(schemaCollection);

 

                  Console.Write("Validating....");

 

                  // Wire up the call back.  The ValidationEvent is fired when the

                  // XmlValidatingReader hits an issue validating a section of the xml

                  reader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler);

                  

                  // Iterate through the xml document

                  while(reader.Read())

                  {

                        Console.Write(".");

                  }

 

                  Console.WriteLine("\n");

 

                  Console.ReadLine();

 

 

            }

 

            private static void reader_ValidationEventHandler(object sender, ValidationEventArgs e)

            {

                  // Report back error information to the console...

                  Console.WriteLine("Bad stuff happened");

                  Console.WriteLine(e.Exception.Message);

                  Console.WriteLine(e.Exception.LineNumber);

 

            }

      }

}

 

--------------------编程问答-------------------- 对于如何创建xml schema,也就是XSD文件。

参见下面的文章
http://www.w3schools.com/Schema/schema_example.asp --------------------编程问答-------------------- 谢谢,问题已经解决了,2楼回复很有帮助,只不过有一点目前的.NET类库中已经不存在XmlValidatingReader了,现在可以用XmlSchemaSet来解决,方法是一样的,还是非常感谢
补充:.NET技术 ,  Web Services
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,