/// <summary>
/// xml 帮助类
/// </summary>
public class XmlUtility
{
string ErrString;
/// <summary>
/// 根据xsd架构文件验证xml的正确性
/// </summary>
/// <param name="xml"></param>
public void CheckXmlValidate(string xml)
{
ErrString = string.Empty;
StringReader sRead = null;
XmlReader xmlRead = null;
XmlSchemaSet schemaSet;
try
{
schemaSet = new XmlSchemaSet();
sRead = new StringReader(xml);
string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Substring(8);
string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(codeBase).Replace("\\bin", ""), "xsd\\PaymentDetails.xsd");
schemaSet.Add(null, path);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventCallBack);
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemaSet;
xmlRead = XmlReader.Create(sRead, settings);
while (xmlRead.Read())
{
}
if (ErrString.ToString() == String.Empty)
{
//Log.WriteLog("验证成功!");
}
else
{
//Log.WriteLog("验证失败!原因可能是:" + ErrString);
}
}
catch (XmlException exec)
{
//Log.WriteLog(exec.Message);
}
finally
{
if (xmlRead != null)
{
xmlRead.Close();
}
}
}
#region private methods
private void ValidationEventCallBack(Object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)//区分是警告还是错误
{
//Log.WriteLog("验证成功!警告:" + e.Message);
}
else
{
ErrString = "Err:" + e.Message;
throw new Exception(ErrString);
}
}
#endregion
}