CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 182

182
Chương 5: XML

failed = true;

// Hiển thị lỗi validation.

Console.WriteLine("Validation error: " + args.Message);

Console.WriteLine();

}

}

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();

}

}

Nếu 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>