/// <summary>
/// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示
/// </summary>
/// <param name="xmlFile">xml文件</param>
/// <param name="xsdFile">xsd文件</param>
/// <param name="namespaceUrl">命名空间,无则默认为null</param>
/// <returns></returns>
public static string XmlValidationByXsd(string xmlFile, string xsdFile, string namespaceUrl = null)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(namespaceUrl, xsdFile);
//验证出错时执行 第一种写法
settings.ValidationEventHandler += new ValidationEventHandler(delegate (object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
break;
case XmlSeverityType.Warning:
break;
}
throw e.Exception;
});
using (XmlReader reader = XmlReader.Create(xmlFile, settings))
{
try
{
while (reader.Read()) ;
}
catch (Exception ex)
{
sb.AppendFormat("{0}|", ex.Message);
}
}
return sb.ToString();
}
/// <summary>
/// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示
/// </summary>
/// <param name="xmlText">xml文本内容</param>
/// <param name="schemaFile">xsd文件</param>
/// <returns></returns>
public static string XmlValidateByXsd(string xmlText, string schemaFile)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, schemaFile);
settings.ValidationEventHandler += (x, y) =>
{
sb.AppendFormat("{0}\n", y.Message);
};
using (XmlReader reader = XmlReader.Create(new StringReader(xmlText), settings))
{
try
{
while (reader.Read()) ;
}
catch (XmlException ex)
{
sb.AppendFormat("{0}\n", ex.Message);
}
}
return sb.ToString();
}
/// <summary>
/// 通过xsd验证xml格式是否正确
/// </summary>
/// <param name="xmldata">xml文本内容</param>
/// <param name="xsdPath">xsd文件</param>
/// <returns></returns>
private bool XMLcheckXsd(string xmldata, string xsdPath)
{
bool rtn = false;
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmldata));
ms.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.Schemas.Add(null, xsdPath);
using (XmlReader xmlReader = XmlReader.Create(ms, settings))
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlReader);
xmlDocument.Validate(ValidationCallBack);
rtn = true;
}
catch(Exception ex)
{
rtn = false;
}
}
return rtn;
}
private void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine(e.Message);
throw e.Exception;
}
C#XSD文件校验XML文件和字符串
最新推荐文章于 2024-04-27 18:57:46 发布