.net – 防止XmlTextReader扩展实体

前端之家收集整理的这篇文章主要介绍了.net – 防止XmlTextReader扩展实体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在不扩展实体的情况下读取 XML文档,对其进行一些操作,然后像最初那样使用未扩展的实体重新保存它.

直接使用XDocument时,无法加载,抛出异常告诉我它有未展开的实体:

XDocument doc = XDocument.Load(file);  // <--- Exception
// ... do some manipulation to doc
doc.Save(file2);

Exception: Reference to undeclared entity ‘entityname’.

@H_502_8@

然后我尝试将XmlTextReader传递给XDocument构造函数,但EntityHandling属性没有“no expand”:

XmlTextReader xmlReader = new XmlTextReader(file));
xmlReader.EntityHandling = EntityHandling.ExpandCharEntities;
XDocument doc = XDocument.Load(xmlReader);

另外,我查看了XmlReader.Create函数,但MSDN说:“Create方法创建的读者扩展了所有实体”.

如何创建不展开实体的XmlReader,或者具有未展开实体的XDocument?

以下对我有用.关键是使用反射来设置内部属性 DisableUndeclaredEntityCheck的值.
XmlDocument document = new XmlDocument();
XmlReaderSettings readerSettings = new XmlReaderSettings()
{
    DtdProcessing = DtdProcessing.Ignore,IgnoreWhitespace = true,};
using (XmlReader reader = XmlReader.Create(inputPath,readerSettings))
{
    PropertyInfo propertyInfo = reader.GetType().GetProperty("DisableUndeclaredEntityCheck",BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    propertyInfo.SetValue(reader,true);
    document.Load(reader);
}
原文链接:https://www.f2er.com/xml/292565.html

猜你在找的XML相关文章