您的位置:首页 > 编程语言 > C#

C#中用schema验证xml的合法性

2017-09-19 16:05 330 查看
class ValidateXML
{
public string ErrString = string.Empty;
public void ValidationEventCallBack(Object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)//区分是警告还是错误
{
//Console.WriteLine("验证成功!警告:" + e.Message);
ErrString += "验证成功!警告:" + e.Message;
}
else
{
// Console.WriteLine("验证失败");
ErrString += "Err:" + e.Message;
}
}

public void CheckXmlValidate(string strRequestXML)
{
//string ErrString = string.Empty;
StringReader sRead = null;
XmlReader xmlRead = null;
XmlSchemaSet schemaSet;

try
{
schemaSet = new XmlSchemaSet();

sRead = new StringReader(strRequestXML);

schemaSet.Add(null, @"MySchema.xsd");

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)
{

Console.WriteLine("验证成功!");
}
else
{
Console.WriteLine("验证失败!原因可能是:" + ErrString);
}
}
catch (XmlException exec)
{
Console.WriteLine(exec.Message);
}
finally
{

if (xmlRead != null)
{

xmlRead.Close();
}
}
}
}

public static void Main(string[] args)
{
ValidateXML vx = new ValidateXML();
//StreamReader sr = new StreamReader(new FileStream(@"test.xml", FileMode.Open));
vx.CheckXmlValidate(File.ReadAllText(@"test.xml"));

PressQtoQuit();
}

public static void PressQtoQuit()
{
Console.WriteLine("Hit Q to exit");
ConsoleKey key;
do
{
key = Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}


Reference from : https://msdn.microsoft.com/en-us/library/as3tta56(v=vs.80).aspx
Reference from : http://www.cnblogs.com/joean/p/4982875.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: