在深入本文之前,需要具备XML和XSD的基础知识。本文将介绍以下内容:
将通过以下步骤进行示例:
首先定义XML文件,命名为Complex.XML:
<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
</Person>
生成XSD的步骤如下:
<xs:schema xmlns:ns0="http://Testing.Message" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Address" type="xs:string" />
<xs:element name="Phone" type="xs:unsignedLong" />
<xs:element name="Email" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
为了检查电子邮件地址是否有效,可以通过正则表达式来实现,将EMAIL标签的类型从String更改为自定义类型:
<xs:element name="Email" type="ValidateEmail" />
定义自定义类型的结构:
<xs:simpleType name="ValidateEmail">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />
</xs:restriction>
</xs:simpleType>
创建一个新的页面“Complex.aspx”,并添加一个名为“lblMsg”的标签。
在Complex.aspx.cs中定义类级别的全局变量:
private int nErrors = 0;
private string strErrorMsg = string.Empty;
public string Errors {
get {
return strErrorMsg;
}
}
在Complex.aspx页面的PageLoad事件中:
if (!IsValidXml(@"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xml", @"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xsd"))
lblMsg.Text = Errors;
else
lblMsg.Text = "Success";
IsValidXml函数定义:
public bool IsValidXml(string xmlPath, string xsdPath) {
bool bStatus = false;
try {
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
rs.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
rs.Schemas.Add(null, XmlReader.Create(xsdPath));
using (XmlReader xmlValidatingReader = XmlReader.Create(xmlPath, rs)) {
while (xmlValidatingReader.Read()) { }
}
if (nErrors > 0) {
throw new Exception(strErrorMsg);
} else {
bStatus = true;
}
} catch (Exception error) {
bStatus = false;
}
return bStatus;
}
事件处理程序体定义,用于处理任何异常:
void ValidationEventHandler(object sender, ValidationEventArgs e) {
if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: ";
else strErrorMsg += "ERROR: ";
nErrors++;
if (e.Exception.Message.Contains("'Email' element is invalid")) {
strErrorMsg = strErrorMsg + getErrorString("Provided Email data is Invalid", "CAPIEMAIL007") + "\r\n";
}
if (e.Exception.Message.Contains("The element 'Person' has invalid child element")) {
strErrorMsg = strErrorMsg + getErrorString("Provided XML contains invalid child element", "CAPINVALID005") + "\r\n";
} else {
strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
}
}
getErrorString:在XML字符串格式中生成自定义错误:
string getErrorString(string erroString, string errorCode) {
StringBuilder errXMl = new StringBuilder();
errXMl.Append("MyError> ERROR_STRING ERROR_CODE ");
errXMl.Replace("ERROR_STRING", erroString);
errXMl.Replace("ERROR_CODE", errorCode);
return errXMl.ToString();
}
现在保存应用程序并运行,使用以下XML。应该在网页上看到SUCCESS消息:
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
</Person>
接下来,修改XML,添加一个未在XSD中定义的额外标签。运行应用程序并查看异常。现在XML将如下所示:
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
<EmpId>123592</EmpId>
</Person>
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.@.com.com</Email>
</Person>