您的位置:首页 > 其它

使用xsd验证xml文件是否规范

2012-12-25 15:22 246 查看
public class XmlValidation
{
StringBuilder sb;
public  string XmlValidationByXsd(string XmlPath,string XsdPath)
{
sb= new StringBuilder();
string strReturnValue = string.Empty;

string dataFile = XmlPath;
string schemaFile = XsdPath;
//备注:这里为xsd验证文件里的命名空间targetNamespace
string namespaceUrl = "http://www.xxx.cn/xxx";

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(namespaceUrl, schemaFile);
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

string errorMessage = "这不是一个合乎规范的数据文件";

XmlReader reader = XmlReader.Create(dataFile, settings);
try
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Document && reader.NamespaceURI != namespaceUrl)
{
strReturnValue = errorMessage;
break;
}
}
}
catch (XmlException ex)
{
sb.AppendFormat("{0}\n", ex.Message);
}
finally
{
reader.Close();
}

if (sb.Length == 0)
strReturnValue = "true";
else
strReturnValue = sb.ToString();

return strReturnValue;
}

void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
{
sb.AppendFormat("{0}\n", e.Message);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: