我正在开发一个系统,该系统将通过Web服务接收XML(XmlDocument)。我不会在硬盘上拥有这个XML(XmlDocument),它将在内存中管理。
我有一个XSD文件来验证从WebService接收到的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,但该字段中存在字符串值,而我没有收到错误提示。
<note xmlns="http://www.w3schools.com">
。 - marc_s