如何使用未定义的命名空间验证xml根元素

时间:2015-07-19 04:16:02

标签: c# xml namespaces schema

有一个XML模式文件" books.xsd"如下:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="bookstore" />
</xs:schema>

有一个XML文件&#34; books1.xml&#34;如下:

<?xml version="1.0" encoding="utf-8"?>
<bookstore xmlns="http://www.contoso.com/books">
</bookstore>

有一个XML文件&#34; books2.xml&#34;如下:

<?xml version="1.0" encoding="utf-8"?>
<bookstoreXXX xmlns="http://www.contoso.com/books">
</bookstoreXXX>

有一个XML文件&#34; books3.xml&#34;如下:

<?xml version="1.0" encoding="utf-8"?>
<bookstoreXXX xmlns="http://www.contoso.com/booksXXX">
</bookstoreXXX>

我使用这些C#代码来测试:

class Program
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("booksN.xml");
        doc.Schemas.Add("http://www.contoso.com/books", "books.xsd");
        doc.Validate(booksSettingsValidationEventHandler);

        Console.WriteLine("\r\nPress ENTER to exit.");
        Console.Read();
    }

    static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.Write("WARNING: ");
            Console.WriteLine(e.Message);
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.Write("ERROR: ");
            Console.WriteLine(e.Message);
        }
    }
}

验证&#34; books1.xml&#34;。

时没有错误

错误&#34;&#39; http://www.contoso.com/books:bookstoreXXX&#39;元素未声明。&#34;当使用validate&#34; books2.xml&#34;。

验证&#34; books3.xml&#34;。

时没有错误

但我想在验证&#34; books3.xml&#34;时出错,例如&#34;&#39; booksstoreXXX&#39;元素未声明。&#34;或&#34;&#39;&#39; http://www.contoso.com/booksXXX&#39;未声明名称空间。&#34;。

如何修改XML架构文件或C#代码?

0 个答案:

没有答案