此代碼根據XSD文件驗證XML文件並返回錯誤和行號。
public static void ValidateXML(Stream stream)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", "yourXSDPath");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(stream, settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
document.Validate(eventHandler);
reader.Close();
}
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{}
try
{
ValidateXML(yourXMLStream);
}
catch (XmlSchemaValidationException ex)
{
Console.WriteLine(String.Format("Line {0}, position {1}: {2}", ex.Message, ex.LineNumber, ex.LinePosition));
}
來源
2010-05-26 21:05:10
jlp
你可以發佈xsd文件嗎? – Numenor 2009-12-29 14:31:49
有趣的問題。你有沒有找到高級別的解決方案?在沒有用線和位置解釋錯誤位置的意義上。謝謝 – robob 2012-06-20 13:43:19