我试图在不扩展实体的情况下读取 XML 文档,对其进行一些操作,然后将其与最初未扩展的实体一起重新保存。
直接使用 XDocument 时,它无法加载,抛出异常告诉我它有未扩展的实体:
XDocument doc = XDocument.Load(file); // <--- Exception
// ... do some manipulation to doc
doc.Save(file2);
例外:引用未声明的实体“entityname”。
然后我尝试通过XmlTextReader
to the XDocument
构造函数,但是EntityHandling
属性没有“不展开”:
XmlTextReader xmlReader = new XmlTextReader(file));
xmlReader.EntityHandling = EntityHandling.ExpandCharEntities;
XDocument doc = XDocument.Load(xmlReader);
另外,我查看了 XmlReader.Create 函数,但 MSDN 说:“由 Create 方法创建的读者展开所有实体”。
如何创建不扩展实体的 XmlReader,或者具有未扩展实体的 XDocument?
以下内容对我有用。关键是使用反射来设置内部属性的值DisableUndeclaredEntityCheck http://referencesource.microsoft.com/#System.Xml/Xml/System/Xml/Core/XmlTextReaderImpl.cs#2ddfbe26b99e28a0.
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)