Sameer Damir
Sameer Damir

Reputation: 1644

Alternatives to XDocument and XmlDocument for loading xml files in C#?

I want to change an attribute inside an xml file using C#.

Here is a sample XML file

<?xml version="1.0" encoding="us-ascii"?>
<Client>
  <Age>25</Age>
  <Weight>50</Weight>
</Client>

I tried loading the xml file using both XmlDocument and XDocument. They both take so much time (more than 5 minutes) to load.

Here is the code I am using to load the file:

string filePath = @"myFile.xml";
XmlDocument xmlData = new XmlDocument();

As per Google, the problem is that XDocument and XmlDocument will load all the DTDs for XML file, and this is why it takes much time. Is there a workaround for this? or maybe any alternative that allows me to change an attribute without loading all the DtDs?

Upvotes: 1

Views: 925

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20812

You can control how DTDs are cached, parsed or used for validation with XmlReaderSettings and still use XDocument.

If you can take the time to cache the DTDs and changing them isn't part of your test, you could take the hit once and cache them.

If that's too much time or they aren't available and they aren't needed for your tests, you could skip DTD processing.

using (var reader = XmlReader.Create(_, 
  new XmlReaderSettings
  {
      DtdProcessing = DtdProcessing.Ignore,
      ValidationType = ValidationType.None,
      //DtdProcessing = DtdProcessing.Parse,
      //ValidationType = ValidationType.DTD,
      XmlResolver = new XmlUrlResolver
      {
          CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable),
          //CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore),
      }
  }))
{
    var doc = XDocument.Load(reader);
    //…
}

XmlReaderSettings has many other properties that sometimes come in handy.

Upvotes: 1

Related Questions