我想使用内联 XML 模式验证字符串,并想处理 XMLSchemaException。我尝试了下面的代码:
String parameter="<HostName>Arasanalu</HostName><AdminUserName>Administrator</AdminUserName>
<AdminPassword>A1234</AdminPassword><PlaceNumber>38</PlaceNumber>"
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
//settings.Schemas.Add(null,"http://www.w3.org/2001/XMLSchema");
XmlSchemaSet sch = new XmlSchemaSet();
sch.Add(null,"http://www.w3.org/2001/XMLSchema");
try
{
// Create the XmlReader object.
XmlReader xmlrdr = XmlReader.Create(new StringReader("<root>" + parameter + "</root>"),
settings);
// Parse the file.
while (xmlrdr.Read());
}
catch (XmlSchemaValidationException ex)
{
Console.WriteLine("The file could not read the value at XML format is not correct due to" + ex);
}
传递无效参数时出现错误“XMLException was unhandled” while (xmlrdr.Read());
。但我只想处理XMLSchemaValidationException
. 请让我知道如何实现这一目标。