0
我的函数在XDocument构造函数上爆炸了。说非空白字符是不允许的。如何根据XSD文件验证XML字符串?
public static bool ValidateXML(string xml, string xsd)
{
StringBuilder sb = new StringBuilder();
bool blnReturn = true;
bool errors = false;
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsd)));
XDocument xmlDoc = new XDocument(XmlReader.Create(new StringReader(xml)));
//validate the XML text against the XSD
xmlDoc.Validate(schemas, (o, e) =>
{
sb.AppendLine(e.Message);
errors = true;
});
//if there are errors, display them and return false
if (errors)
{
MessageBox.Show("XML did not parse cleanly. Please fix the following errors.\n\n" + sb.ToString(), "XML Parsing Results");
blnReturn = false;
}
else
{
MessageBox.Show("XML Parsed cleanly. Saving to file.", "XML Parsing Results");
}
return blnReturn;
}
我通过粘贴到W3Schools XML验证器中,检查了插入到函数中的文本。它干净地验证。难道这是因为它从一个RTF控件拉出来,并且可能有不可见的格式化字符? –
我想你可能已经回答了你自己的问题。创建一个单元测试,直接传入你的“有效”xml,看看它是否有效。 – theoretical