. Net uses DTD to verify XML
Find the answer at the Microsoft technical support center.
1. Create a book. xml file, and save the DTD as a file. Add the DTD path to the XML file.
<! 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. generate C # Verification Code
Public bool validate (string filename)
{
// The verification error handling is omitted and can be processed directly in the current Code segment.
// System. xml. schema. validationeventhandler eventhandler = new system. xml. schema. validationeventhandler (myvalidationeventhandler );
System. xml. xmlreader reader = NULL;
Try
{
// Declare the verification variable
System. xml. xmlreadersettings settings = new system. xml. xmlreadersettings ();
Settings. prohibitdtd = false; // an exception occurs when you allow DTD verification to be set to true.
// Set the verification type to DTD. If verification is not required, it can be set to validationtype. None.
Settings. validationtype = system. xml. validationtype. DTD;
// Settings. validationeventhandler + = eventhandler;
// Create an XML read variable
Reader = system. xml. xmlreader. Create (server. mappath (filename), settings );
// Assign the value of reader to xmldocument to facilitate processing. xmlreader has poor processing capability. If it is its name, it can only read
// If the verification fails, a validation exception is thrown.
// However, the data is still read in xmldocument and can still be processed
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;
}