.net – 防止XmlTextReader扩展实体
发布时间:2020-12-16 07:48:41 所属栏目:百科 来源:网络整理
导读:我试图在不扩展实体的情况下读取 XML文档,对其进行一些操作,然后像最初那样使用未扩展的实体重新保存它. 直接使用XDocument时,无法加载,抛出异常告诉我它有未展开的实体: XDocument doc = XDocument.Load(file); // --- Exception// ... do some manipulati
我试图在不扩展实体的情况下读取
XML文档,对其进行一些操作,然后像最初那样使用未扩展的实体重新保存它.
直接使用XDocument时,无法加载,抛出异常告诉我它有未展开的实体: XDocument doc = XDocument.Load(file); // <--- Exception // ... do some manipulation to doc doc.Save(file2);
然后我尝试将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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |