在使用XDocument.Load()加载文件之前,可以使用以下方法测试文件以查看它是否是有效的XML文件:
System.Xml.XmlReader
和System.Xml.XmlWriter
类:using System.Xml;
public static bool IsValidXml(string xml)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
try
{
while (reader.Read()) { }
return true;
}
catch (XmlException)
{
return false;
}
}
private static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
throw new ApplicationException("Invalid XML: " + e.Message);
}
System.Xml.Schema.XmlSchemaSet
类:using System.Xml;
using System.Xml.Schema;
public static bool IsValidXml(string xml)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.w3.org/2001/XMLSchema", "http://www.w3.org/2001/XMLSchema.xsd");
settings.Schemas = schemaSet;
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
try
{
while (reader.Read()) { }
return true;
}
catch (XmlException)
{
return false;
}
}
private static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
throw new ApplicationException("Invalid XML: " + e.Message);
}
这两种方法都可以用于测试XML文件的有效性,并在发现无效时抛出异常。在实际应用中,可以根据需要选择合适的方法进行测试。
领取专属 10元无门槛券
手把手带您无忧上云