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