.net 用dtd驗證xml
還是在微軟支援人員中心找到答案.
1.建立book.xml檔案,dtd也可以另存新檔一個檔案,xml檔案裡面加上dtd路徑就可以了
<!DOCTYPE Product SYSTEM "book.dtd">
<!DOCTYPE bookstore [
<!ELEMENT bookstore (book)*>
<!ELEMENT book (title,author,price)>
<!ATTLIST book genre CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>]>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
2.產生C#驗證代碼
public bool Validate(string filename)
{
//省略了驗證出錯處理 直接在當前程式碼片段處理即可
// System.Xml.Schema.ValidationEventHandler eventHandler = new System.Xml.Schema.ValidationEventHandler(MyValidationEventHandler);
System.Xml.XmlReader reader = null;
try
{
// 聲明驗證變數
System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
settings.ProhibitDtd = false;//允許dtd驗證 設為true會產生異常
//驗證類型設為DTD 如果不需要驗證可以設為ValidationType.None
settings.ValidationType = System.Xml.ValidationType.DTD;
//settings.ValidationEventHandler += eventHandler;
//建立xml讀取變數
reader = System.Xml.XmlReader.Create(Server.MapPath(filename), settings);
// 將reader賦值給XmlDocument,方便處理,xmlreader本身處理能力很弱,如其名,只能讀
// 驗證失敗將會引發一個validation異常
// 然而資料還是讀到了XmlDocument裡面的,仍然可以處理
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(reader); }
catch(System.Xml.XmlException e)
{
Response.Write(e.Message);
return false;
}
catch(System.Xml.Schema.XmlSchemaException e)
{
Response.Write(e.Message);
return false;
}
finally
{
if (reader != null) reader.Close();
}
return true;
}