如何根据XSD文件验证XML字符串?
我下面的函数在XDocument构造函数上爆炸了。表示不允许使用非空白字符如何根据XSD文件验证XML字符串?,xml,visual-studio-2010,c#-4.0,xsd,Xml,Visual Studio 2010,C# 4.0,Xsd,我下面的函数在XDocument构造函数上爆炸了。表示不允许使用非空白字符 public static bool ValidateXML(string xml, string xsd) { StringBuilder sb = new StringBuilder(); bool blnReturn = true; bool errors = false; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.
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;
}
我看代码没有任何问题。您的xml字符串可能无效。非空白字符错误表示xml元素之间有文本字符。例:
<blah>This text is okay</blah>This text isn't
<blah>More text</blah>
通过粘贴到W3XML验证器中,我仔细检查了插入到函数中的文本。它干净地验证了。可能是因为它来自RTF控件,并且可能有不可见的格式字符吗?我想您可能已经回答了自己的问题。创建一个直接传入有效xml的单元测试,看看它是否有效。