我在修復程序中的警告,顯然xmlvalidating reader和xmlschemacollection已過時。問題是,我不太清楚如何。這裏試圖用xmlschemaset和xmlreader.create中的新模型「模仿」以前的驗證函數。我首先聲明一個模式,並使用targeturi字符串進行設置,然後將其添加到模式集,同時設置驗證事件處理程序。我認爲我的問題是設置讀者和輸入流。我知道如何使用xmlvalidating reader來完成它,但如果我想修復這些警告,那不是一個選項。這是代碼和嘗試。在測試過程中,只使用了新的驗證xml代碼,舊代碼被註釋掉了。如何使用xmlschemaset和xmlreader.create根據xsd模式驗證xml
// New Validation Xml.
string xsd_file = filename.Substring(0, filename.Length - 3) + "xsd";
XmlSchema xsd = new XmlSchema();
xsd.SourceUri = xsd_file;
XmlSchemaSet ss = new XmlSchemaSet();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
ss.Add(xsd);
if (ss.Count > 0)
{
XmlTextReader r = new XmlTextReader(filename2);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(ss);
settings.ValidationEventHandler +=new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create(filename2, settings);
while (reader.Read())
{
}
reader.Close();
}
// Old Validate XML
XmlSchemaCollection sc = new XmlSchemaCollection();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
sc.Add(null, xsd_file);
if (sc.Count > 0)
{
XmlTextReader r = new XmlTextReader(filename2);
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.Schemas.Add(sc);
v.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
while (v.Read())
{
}
v.Close();
}
private void ValidationCallBack(object sender, ValidationEventArgs e)
{
// If Document Validation Fails
isvalid = false;
MessageConsole.Text = "INVALID. Check message and datagridview table.";
richTextBox1.Text = "The document is invalid: " + e.Message;
}
不幸的是,當我運行該程序,並嘗試驗證無效XML文檔,它給了我這樣一個錯誤:「‘URNLookup’元素未聲明。」 URNLookup元素是xml文件的根元素。我總是可以回到舊的驗證方法,但這些警告讓我害怕。
任何幫助都很讚賞。先謝謝你!如果我錯過了任何信息,我會很樂意提供更多信息。
- tf.rz(.NET 3.5 SP1,Visual Studio的C#2008)
這問題現在解決了! – 2011-06-01 22:38:48