开发者

What is the differece between these XML validation methods?

开发者 https://www.devze.com 2023-02-25 01:21 出处:网络
I try to validate XML against XSD. I found several ways to do that. These two works well writing all errors so what is intend use of each?

I try to validate XML against XSD. I found several ways to do that. These two works well writing all errors so what is intend use of each?

XmlDocument and XmlSchema classes

XmlDocument document = new XmlDocument();
document.Load(xmlFilePath);    
document.Schemas.Add(@namespace,schemaFilePath);
document.Validate(ValidationHandler);
-----    
public void ValidationHandler(object sender, ValidationEventArgs e)
{
  Console.WriteLine(e.Message);
}

XmlReaderSettings class

Here I can make some settings and validation happens as early as Load() is executed.

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
settings.Schemas.Add(@namespace, schemaFilePath));
settings.ValidationType = ValidationType.Schema;
X开发者_运维问答mlReader reader = XmlReader.Create(xmlFilePath, settings);
document.Load(reader);
reader.Close();
-----
public void ValidationHandler(object sender, ValidationEventArgs e)
{
  Console.WriteLine(e.Message);
}


The difference is between the XmlReader and XmlDocument classes. XmlReader streams the XML and reads it one node at a time. XmlDocument on the other hand reads the whole XML into memory and works with that. So, generally, XmlDocument is easier to use, but is unsuitable for huge files.

As far as validation is concerned, it seems the classes are comparable, so either choose the one that is easier to use for you (probably XmlDocument) or choose XmlReader if you expect big files or if low memory consumption is important.

Also, to validate using XmlReader, you don't need to use XmlDocument.Load() as you do, something like while (reader.Read()) { } should be sufficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消