使用XmlReader使用内联XML架构验证XML字符串
本文关键字:XML 验证 字符串 XmlReader 使用 | 更新日期: 2023-09-27 18:25:59
我想使用内联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);
}
在传递无效参数while (xmlrdr.Read());
时,我收到错误"XMLException未处理"。但我只想处理XMLSchemaValidationException
。请告诉我怎样才能做到这一点。
您必须添加一个ValidationEventHandler
String parameter=@"<HostName>Arasanalu</HostName>
<AdminUserName>Administrator</AdminUserName>
<AdminPassword>A1234</AdminPassword>
<PlaceNumber>38</PlaceNumber>";
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing= DtdProcessing.Parse;
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.AllowXmlAttributes |
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.Schemas.Add(null,XmlReader.Create(new StringReader(
@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""root"">
<xs:complexType>
<xs:sequence>
<xs:element name=""HostName"" type=""xs:string"" />
<xs:element name=""AdminUserName"" type=""xs:string"" />
<xs:element name=""AdminPassword"" type=""xs:string"" />
<xs:element name=""PlaceNumber"" type=""xs:positiveInteger"" />
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>"), settings));
settings.ValidationEventHandler += (s,e) =>
{
throw new XmlSchemaValidationException(e.Message);
};
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);
}