我正在开发一个将通过网络服务接收 XML (XmlDocument) 的系统。我不会在硬盘上有这个 XML (XmlDocument)。它将在内存上进行管理。
我有一个 XSD 文件来验证从我的 Web 服务接收到的 XML (XmlDocument)。我正在尝试做一个例子来说明如何验证这个 Xml。
我的 XML:
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
还有我的 XSD:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
正如我们所见,我将body 字段设置为int,只是为了模拟错误。
好吧,为了尝试找出错误,我有以下代码:
//event handler to manage the errors
private static void verifyErrors(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
MessageBox.Show(args.Message);
}
在点击按钮时,我有:
private void button1_Click(object sender, EventArgs e)
{
try
{
// my XmlDocument (in this case I will load from hardisk)
XmlDocument xml = new XmlDocument();
// load the XSD schema.. is this right?
xml.Schemas.Add("http://www.w3schools.com", "meuEsquema.xsd");
// Load my XML from hardisk
xml.Load("meusDados.xml");
// event handler to manage the errors from XmlDocument object
ValidationEventHandler veh = new ValidationEventHandler(verificaErros);
// try to validate my XML.. and the event handler verifyError will show the error
xml.Validate(veh);
}
catch {
// do nothing.. just to test
}
}
问题是我将 body 字段更改为 int,但该字段中有一个字符串值,我没有收到错误。
最佳答案
问题是 XML 命名空间。
在您的 XSD 中,您将 targetNamespace=
和 xmlns=
定义为 "http://www.w3schools.com"
:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
但是 - 您的 XML 文档不包含任何 XML 命名空间。
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
所以基本上,XSD 根本不验证这个 XML。
您需要从 XSD 中删除这些命名空间:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
或者,将 XSD 中定义的默认 XML 命名空间(无前缀)添加到 XML:
<?xml version="1.0"?>
<note xmlns="http://www.w3schools.com">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
如果您的 XSD 中有 XML namespace ,那么它们也必须出现在 XML 中 - 反之亦然。
一旦您执行了一种或另一种解决方案,您应该会收到类似于以下内容的验证错误:
Validation error: The 'body' element is invalid - The value 'Don't forget me this weekend!' is invalid according to its datatype
'http://www.w3.org/2001/XMLSchema:int' - The string 'Don't forget me this weekend!' is not a valid Int32 value.
关于xml - 使用 XSD 验证 XmlDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3303494/