我们在开发过程中,经常要维护XML文件,有的可能是手工维护,这样就涉及到XML文档正确性的问题,如果有人在添加节点的时候,不小心漏掉了结束节点、少打了个“<”等等,如果XML文件足够大,人为校验显然是不合适的,那么验证XML文档是否规范,最懒的办法,就是用DOM去Load这个文档,看看有没有Catch,这样虽然可以达到验证文档是否正确的目的,但是错误信息不够详细,今天我介绍一下如何利用XmlReader来验证XML文档的正确性
首先,关于XmlReader以及XmlReaderSettings的介绍可以参考MSDN
XmlReader(http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx)
XmlReaderSettings(http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.aspx)
其实方法很简单,就是让Reader不停的去读取XML文档,然后在ValidationEventHandler事件中,根据ValidationEventArgs中的Severity属性来判断是Warning还是Error
具体代码如下
TestXmlReader.Designer.cs
namespace testApplication1 { partial class TestXmlReader { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { this.txtXmlPath = new System.Windows.Forms.TextBox(); this.btnBrowserXml = new System.Windows.Forms.Button(); this.lblXmlPath = new System.Windows.Forms.Label(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPageAll = new System.Windows.Forms.TabPage(); this.tabPageError = new System.Windows.Forms.TabPage(); this.tabPageWarning = new System.Windows.Forms.TabPage(); this.btnOK = new System.Windows.Forms.Button(); this.lbAll = new System.Windows.Forms.ListBox(); this.lbError = new System.Windows.Forms.ListBox(); this.lbWarning = new System.Windows.Forms.ListBox(); this.tabControl1.SuspendLayout(); this.tabPageAll.SuspendLayout(); this.tabPageError.SuspendLayout(); this.tabPageWarning.SuspendLayout(); this.SuspendLayout(); // // txtXmlPath // this.txtXmlPath.Location = new System.Drawing.Point(112, 43); this.txtXmlPath.Name = "txtXmlPath"; this.txtXmlPath.ReadOnly = true; this.txtXmlPath.Size = new System.Drawing.Size(410, 19); this.txtXmlPath.TabIndex = 0; // // btnBrowserXml // this.btnBrowserXml.Location = new System.Drawing.Point(540, 41); this.btnBrowserXml.Name = "btnBrowserXml"; this.btnBrowserXml.Size = new System.Drawing.Size(75, 23); this.btnBrowserXml.TabIndex = 1; this.btnBrowserXml.Text = "browser.."; this.btnBrowserXml.UseVisualStyleBackColor = true; this.btnBrowserXml.Click += new System.EventHandler(this.btnBrowserXml_Click); // // lblXmlPath // this.lblXmlPath.Location = new System.Drawing.Point(47, 46); this.lblXmlPath.Name = "lblXmlPath"; this.lblXmlPath.Size = new System.Drawing.Size(59, 16); this.lblXmlPath.TabIndex = 2; this.lblXmlPath.Text = "XmlPath:"; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPageAll); this.tabControl1.Controls.Add(this.tabPageError); this.tabControl1.Controls.Add(this.tabPageWarning); this.tabControl1.Location = new System.Drawing.Point(49, 68); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(634, 419); this.tabControl1.TabIndex = 3; // // tabPageAll // this.tabPageAll.Controls.Add(this.lbAll); this.tabPageAll.Location = new System.Drawing.Point(4, 21); this.tabPageAll.Name = "tabPageAll"; this.tabPageAll.Padding = new System.Windows.Forms.Padding(3); this.tabPageAll.Size = new System.Drawing.Size(626, 394); this.tabPageAll.TabIndex = 0; this.tabPageAll.Text = "ALL"; this.tabPageAll.UseVisualStyleBackColor = true; // // tabPageError // this.tabPageError.Controls.Add(this.lbError); this.tabPageError.Location = new System.Drawing.Point(4, 21); this.tabPageError.Name = "tabPageError"; this.tabPageError.Padding = new System.Windows.Forms.Padding(3); this.tabPageError.Size = new System.Drawing.Size(626, 394); this.tabPageError.TabIndex = 1; this.tabPageError.Text = "Error"; this.tabPageError.UseVisualStyleBackColor = true; // // tabPageWarning // this.tabPageWarning.Controls.Add(this.lbWarning); this.tabPageWarning.Location = new System.Drawing.Point(4, 21); this.tabPageWarning.Name = "tabPageWarning"; this.tabPageWarning.Padding = new System.Windows.Forms.Padding(3); this.tabPageWarning.Size = new System.Drawing.Size(626, 394); this.tabPageWarning.TabIndex = 2; this.tabPageWarning.Text = "Warning"; this.tabPageWarning.UseVisualStyleBackColor = true; // // btnOK // this.btnOK.Location = new System.Drawing.Point(628, 41); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(55, 23); this.btnOK.TabIndex = 4; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // lbAll // this.lbAll.Dock = System.Windows.Forms.DockStyle.Fill; this.lbAll.FormattingEnabled = true; this.lbAll.ItemHeight = 12; this.lbAll.Location = new System.Drawing.Point(3, 3); this.lbAll.Name = "lbAll"; this.lbAll.Size = new System.Drawing.Size(620, 388); this.lbAll.TabIndex = 0; // // lbError // this.lbError.Dock = System.Windows.Forms.DockStyle.Fill; this.lbError.FormattingEnabled = true; this.lbError.ItemHeight = 12; this.lbError.Location = new System.Drawing.Point(3, 3); this.lbError.Name = "lbError"; this.lbError.Size = new System.Drawing.Size(620, 388); this.lbError.TabIndex = 1; // // lbWarning // this.lbWarning.Dock = System.Windows.Forms.DockStyle.Fill; this.lbWarning.FormattingEnabled = true; this.lbWarning.ItemHeight = 12; this.lbWarning.Location = new System.Drawing.Point(3, 3); this.lbWarning.Name = "lbWarning"; this.lbWarning.Size = new System.Drawing.Size(620, 388); this.lbWarning.TabIndex = 2; // // TestXmlReader // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(738, 518); this.Controls.Add(this.btnOK); this.Controls.Add(this.tabControl1); this.Controls.Add(this.lblXmlPath); this.Controls.Add(this.btnBrowserXml); this.Controls.Add(this.txtXmlPath); this.Name = "TestXmlReader"; this.Text = "TestXmlReader"; this.tabControl1.ResumeLayout(false); this.tabPageAll.ResumeLayout(false); this.tabPageError.ResumeLayout(false); this.tabPageWarning.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtXmlPath; private System.Windows.Forms.Button btnBrowserXml; private System.Windows.Forms.Label lblXmlPath; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPageAll; private System.Windows.Forms.TabPage tabPageError; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.TabPage tabPageWarning; private System.Windows.Forms.ListBox lbAll; private System.Windows.Forms.ListBox lbError; private System.Windows.Forms.ListBox lbWarning; } }
TestXmlReader.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; using System.Xml.Schema; using System.Threading; namespace testApplication1 { public partial class TestXmlReader : Form { public TestXmlReader() { InitializeComponent(); } private void btnBrowserXml_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "xml file(*.xml)|*.xml"; if (dlg.ShowDialog() == DialogResult.OK) { this.txtXmlPath.Text = dlg.FileName; } } private void btnOK_Click(object sender, EventArgs e) { if (!File.Exists(this.txtXmlPath.Text)) { MessageBox.Show("Please select exists file!!!"); } this.lbAll.Items.Clear(); this.lbError.Items.Clear(); this.lbWarning.Items.Clear(); Run(); } private void Run() { XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.IgnoreComments = true; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack); try { try { reader = XmlReader.Create(this.txtXmlPath.Text, settings); while (reader.Read()) { Application.DoEvents(); if (reader.NodeType == XmlNodeType.Element) { this.lbAll.Items.Add(Environment.NewLine); this.lbAll.Items.Add(String.Format("Node Start : {0}(Depth : {1})", reader.LocalName, reader.Depth)); this.lbAll.Items.Add(Environment.NewLine); if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); this.lbAll.Items.Add(Environment.NewLine); this.lbAll.Items.Add(String.Format("/t{0}{1}", reader.Name, reader.Value)); this.lbAll.Items.Add(Environment.NewLine); } this.lbAll.Items.Add(Environment.NewLine); reader.MoveToElement(); } } else if (reader.NodeType == XmlNodeType.EndElement) { this.lbAll.Items.Add(Environment.NewLine); this.lbAll.Items.Add(String.Format("Node End : {0}", reader.LocalName)); this.lbAll.Items.Add(Environment.NewLine); this.lbAll.SelectedIndex = this.lbAll.Items.Count - 1; } } } catch (Exception exception) { this.lbError.Items.Add(Environment.NewLine); this.lbError.Items.Add(String.Format("***Error: {0}/n", exception.Message)); this.lbError.Items.Add(Environment.NewLine); } } finally { if (reader != null) { reader.Close(); } this.lbAll.SelectedIndex = this.lbAll.Items.Count - 1; } } private void ValidationCallBack(object sender, ValidationEventArgs args) { XmlReader reader = (XmlReader)sender; if (args.Severity == XmlSeverityType.Warning) { this.lbWarning.Items.Add(String.Format("***Warning: {0}/n", args.Message)); this.lbWarning.Items.Add(String.Format("***Value: {0}/n", reader.Value)); this.lbWarning.Items.Add(String.Format("***LineNumber: {0}/n", args.Exception.LineNumber)); } else { this.lbError.Items.Add(String.Format("***Error: {0}/n", args.Message)); this.lbError.Items.Add(String.Format("***Value: {0}/n", reader.Value)); this.lbError.Items.Add(String.Format("***LineNumber: {0}/n", args.Exception.LineNumber)); } } } }
欢迎转载,请注明出处~~