我已经尝试解决这个问题几个小时了,问题是我的验证过程并没有真正考虑到我在限制内输入的任何内容。
这是我的XSD:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://tempuri.org/myxmltest">
<xs:element name="Students_With_Preferences-xml">
<xs:complexType>
<xs:sequence>
<xs:element name="Student-xml" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="District"/>
<xs:element name="Preferences">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="5"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Xml示例:
<?xml version="1.0" encoding="utf-8"?>
<Students_With_Preferences-xml xmlns="http://tempuri.org/myxmltest">
<Student-xml>
<District>b</District>
<Preferences>(sc1,20)|(sc2,15)</Preferences>
</Student-xml>
<Student-xml>
<District>d</District>
<Preferences>(sc2,15)|(sc1,10)</Preferences>
</Student-xml>
</Students_With_Preferences-xml>
正如您所看到的,只允许使用长度为5的元素,但是当我运行我的代码时,它允许任何长度。 为了清楚起见,其他一切都正确验证,只是这个恼人的错误。
我尝试使用正则表达式选项解决此问题,但您猜测它不起作用。
验证码(C#):
private Boolean ValidateXML(HttpPostedFileBase file, string xsd_path)
{
bool errors = false;
string filename = "";
XmlSchemaSet schemas = new XmlSchemaSet();
XmlDocument xml_doc = new XmlDocument();
try
{
filename = file.FileName;
schemas.Add("", xsd_path);
xml_doc.Load(file.InputStream);
foreach (XmlNode node in xml_doc.ChildNodes.Item(1).ChildNodes)
{
XDocument doc = XDocument.Parse(node.OuterXml);
doc.Validate(schemas, (o, e) =>
{
ViewBag.msg = "Error validating - " + filename + " - " + e.Message;
errors = true;
});
if (errors) break;
}
}
catch (Exception ex)
{
errors = true;
string msg = "Error validating - " + filename + " - " + ex.Message;
throw new Exception(msg);
}
if (!errors)
{
ViewBag.msg = filename + " was validated succesfully";
}
return !errors;
}
我非常感谢有关如何解决此问题的任何帮助,谢谢!