简体   繁体   English

XDocument和XmlDocument的替代方案,用于在C#中加载xml文件?

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

I want to change an attribute inside an xml file using C#. 我想使用C#更改xml文件中的属性。

Here is a sample XML file 这是一个示例XML文件

<?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 . 我尝试同时使用XmlDocumentXDocument加载xml文件。 They both take so much time (more than 5 minutes) to load. 它们都需要花费大量时间(超过5分钟)来加载。

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. 对于Google而言,问题在于XDocumentXmlDocument将加载XML文件的所有DTD,这就是为什么要花费很多时间的原因。 Is there a workaround for this? 有没有解决方法? or maybe any alternative that allows me to change an attribute without loading all the DtDs? 还是任何允许我在不加载所有DtD的情况下更改属性的替代方法?

You can control how DTDs are cached, parsed or used for validation with XmlReaderSettings and still use XDocument . 您可以使用XmlReaderSettings来控制DTD的缓存,解析或用于验证的方式,并且仍然使用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. 如果您可以花时间缓存DTD,而更改DTD不在测试范围之内,则可以一次点击匹配项并将其缓存。

If that's too much time or they aren't available and they aren't needed for your tests, you could skip DTD processing. 如果时间太多或它们不可用并且测试不需要它们,则可以跳过DTD处理。

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. XmlReaderSettings具有许多其他有时会派上用场的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM