无法在XmlTextReader上设置设置?

时间:2015-06-05 06:57:36

标签: c# .net xml xmldocument xmlreader

我需要在XmlTextReader上设置MaxCharactersFromEntities,这是我到目前为止的代码:

xmlDocument = new XmlDocument();

xmlTextReader = new XmlTextReader(fileInfo.FullName);
xmlTextReader.Settings = new XmlReaderSettings();
xmlTextReader.Settings.MaxCharactersFromEntities = 0;
var vr = new XmlValidatingReader(xmlTextReader);
vr.ValidationType = ValidationType.None;
vr.EntityHandling = EntityHandling.ExpandEntities;

xmlDocument.Load(vr);

Settings属性是只读的,因此无法设置它的null?这应该如何运作?

2 个答案:

答案 0 :(得分:2)

您应该首先在构建XmlReaderSettings实例时传递XmlReader个实例,而不是稍后更新读者的Settings属性 - 这是不可能的,因为该物业没有setter-:

var xmlDocument = new XmlDocument();

//create XmlReaderSettings first
var settings = new XmlReaderSettings();
settings.MaxCharactersFromEntities = 80; //0 doesn't make sense here, as it's the default value

//create XmlReader later, passing the pre-defined settings
var xmlReader = XmlReader.Create(fileInfo.FullName, settings);

//the rest of the codes remain untouched
var vr = new XmlValidatingReader(xmlReader);
vr.ValidationType = ValidationType.None;
vr.EntityHandling = EntityHandling.ExpandEntities;

xmlDocument.Load(vr);

答案 1 :(得分:1)

您应该使用XmlReader.Create(string, XmlReaderSettings)代替创建您的阅读器实例。

来自MSDN参考:

  

从.NET Framework 2.0开始,我们建议您使用   而是System.Xml.XmlReader类。

我们的想法是使用基类XmlReader的Create(...)工厂方法,而不是直接实例化派生类。另请参阅factory method pattern了解更多信息。

由于XmlValidatingReader在构造函数中占用XmlReader,因此其余代码不受影响。

所以你应该最终得到像:

xmlDocument = new XmlDocument();

XmlReaderSettings settings = new XmlReaderSettings();
settings.MaxCharactersFromEntities = 0;
XmlReader reader = XmlReader.Create(fileInfo.FullName, settings);

var vr = new XmlValidatingReader(reader);
vr.ValidationType = ValidationType.None;
vr.EntityHandling = EntityHandling.ExpandEntities;

xmlDocument.Load(vr);