我正在尝试根据其架构验证Xml文件。 这是我的代码:
private readonly List<string> validationErrors = new List<string>();
public bool TryValidate(string xml, string schemaLocation, ref List<string> errors)
{
var document = new XmlDocument();
document.LoadXml(xml);
var schemaReader = new XmlTextReader(schemaLocation);
var settings = new XmlReaderSettings {CloseInput = true};
settings.ValidationEventHandler += Handler;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, schemaReader);
var stringReader = new StringReader(xml);
using (var validatingReader = XmlReader.Create(stringReader, settings))
{
while (validatingReader.Read())
{
}
}
errors = validationErrors;
return errors.Count == 0;
}
private const string Format = "Line: {0}, Position: {1} \"{2}\"";
private void Handler(object sender, ValidationEventArgs e)
{
if (e.Severity != XmlSeverityType.Error)
{
return;
}
validationErrors.Add(string.Format(Format,
e.Exception.LineNumber,
e.Exception.LinePosition,
e.Exception.Message));
}
架构对BusinessType元素具有以下限制:
<xs:element name="BusinessType">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="15"/>
<xs:enumeration value="not specified"/>
<xs:enumeration value="Sole trader"/>
<xs:enumeration value="Partnership"/>
<xs:enumeration value="Limited company"/>
</xs:restriction>
</xs:simpleType>
<xs:element>
但实际的Xml实例文件包含其中包含零的元素:
<BusinessType>0</BusinessType>
然而,当我运行验证代码时,它会通过模式验证(即没有发现错误)? 编辑 - 作为测试,我也完全重命名了其中一个元素,但它仍然没有生成错误!
有谁知道为什么会这样?
非常感谢