/// <summary>
/// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示
/// </summary>
/// <param name="xmlFile">xml文件</param>
/// <param name="xsdFile">xsd文件</param>
/// <param name="namespaceUrl">命名空间,无则默认为null</param>
/// <returns></returns>
public 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 += (x, y) =>
{
sb.AppendFormat("{0}", y.Message);
};
using (XmlReader reader = XmlReader.Create(xmlFile, settings))
{
try
{
while (reader.Read()) ;
}
catch (XmlException ex)
{
sb.AppendFormat("{0}", ex.Message);
}
}
return sb.ToString();
}
C# xsd验证xml格式
最新推荐文章于 2023-04-20 14:02:37 发布