Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Dưới đây là cách sử dụng lớp này để xác nhận tính hợp lệ của danh mục sản phẩm: using System; public class ValidateXml { private static void Main() { ConsoleValidator consoleValidator = new ConsoleValidator(); Console.WriteLine("Validating ProductCatalog.xml."); bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd"); if (!success) { Console.WriteLine("Validation failed."); }else { Console.WriteLine("Validation succeeded."); } Console.ReadLine(); } } . | Dưới đây là cách sử dụng lớp này đê xác nhận tính hợp lệ của danh mục sản phâm using System public class ValidateXml private static void Main ConsoleValidator consoleValidator new ConsoleValidator Console.WriteLine Validating ProductCatalog.xml. bool success consoleValidator.ValidateXml ProductCatalog.xml ProductCatalog.xsd if success Console.WriteLine Validation failed. else Console.WriteLine Validation succeeded. Console.ReadLine Neu tài liệu hợp lệ thì sẽ không có thông báo nào xuất hiện và biến success sẽ được thiết lập thành true. Nhưng xét xem điều gì sẽ xảy ra nếu bạn sử dụng một tài liệu phá vỡ các quy tắc Schema chẳng hạn file ProductCatalog_Invalid.xml như sau xml version 1.0 productCatalog catalogName Acme Fall 2003 Catalog catalogName expiryDate Jan 1 2004 expiryDate products product id 1001 productName Magic Ring productName productPrice 342.10 productPrice inStock true inStock product product id 1002 productName Flying Carpet productName productPrice 982.99 productPrice inStock Yes inStock product products productCatalog Neu bạn kiểm tra tài liệu này biến success sẽ được thiết lập thành false và kết xuất sẽ cho biết các lỗi Validating ProductCatalog_Invalid.xml. Validation error The expiryDate element has an invalid value according to its data type. An error occurred at file I CSharp Chuong05 05-08 bin Debug ProductCatalog_Invalid.xml 4 30 . Validation error The productPrice element has an invalid value according to its data type. An error occurred at file I CSharp Chuong05 05-08 bin Debug ProductCatalog_Invalid.xml 9 36 . Validation error The inStock element has an invalid value according to its data type. An error occurred at file I CSharp Chuong05 05-08 bin Debug ProductCatalog_Invalid.xml 15 27 . Validation failed. Cuối cùng nếu muốn xác nhận tính hợp lệ của một tài liệu XML và rồi xử lý nó bạn có thể sử dụng XmlValidatingReader để quét tài liệu khi nó được đọc vào một XmlDocument trong-bộ-nhớ XmlDocument doc new XmlDocument XmlTextReader r new .