prevent的XmlTextReader从扩大实体实体、prevent、XmlTextReader

由网友(爆菊高手)分享简介:我想读一个XML文档不扩大实体,做一些操作它,并重新保存其与未展开的实体,因为他们最初。在直接使用的XDocument,它加载失败,抛出一个异常,告诉我它未膨胀的实体:的XDocument DOC = XDocument.Load(文件); //< ---异常// ...做一些操作,以文档doc.Save(文...

我想读一个XML文档不扩大实体,做一些操作它,并重新保存其与未展开的实体,因为他们最初。

在直接使用的XDocument,它加载失败,抛出一个异常,告诉我它未膨胀的实体:

 的XDocument DOC = XDocument.Load(文件); //< ---异常
// ...做一些操作,以文档
doc.Save(文件2);
 

  

例外:引用了未声明的实体'的entityName

然后我试图通过的XmlTextReader 的XDocument 的构造函数,但 EntityHandling 属性没有不扩大:

 的XmlTextReader的XmlReader =新的XmlTextReader(文件));
xmlReader.EntityHandling = EntityHandling.ExpandCharEntities;
的XDocument DOC = XDocument.Load(XmlReader的);
 
pr cs4 怎么改输出视频尺寸啊,急

另外,我还看了看XmlReader.Create功能,但MSDN说:通过创建方法来创建读者展开所有实体

如何创建一个不扩大实体,或与实体的XDocument一个的XmlReader没有展开?

解决方案

下面为我工作。关键是使用反射来设置一个内部属性的值 DisableUndeclaredEntityCheck

  XmlDocument的文档=新的XmlDocument();
XmlReaderSettings readerSettings =新XmlReaderSettings()
{
    DtdProcessing = DtdProcessing.Ignore,
    IgnoreWhitespace = TRUE,
};
使用(XmlReader的读者= XmlReader.Create(inputPath,readerSettings))
{
    。的PropertyInfo的PropertyInfo = reader.GetType()的getProperty(DisableUndeclaredEntityCheck,BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic可);
    propertyInfo.SetValue(读者,真正的);
    document.Load(读卡器);
}
 

I am trying to read a XML document without expanding the entities, do some manipulations to it, and re-save it with the unexpanded entities as they were initially.

When using the XDocument directly, it fails to load, throwing an exception tell me it has unexpanded entities:

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

Exception: Reference to undeclared entity 'entityname'.

Then I tried to pass the XmlTextReader to the XDocument constructor, but the EntityHandling property does not have "no expand":

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

Also, I have looked at the XmlReader.Create function, but MSDN says: "readers created by the Create method expand all entities".

How can I create a XmlReader that does not expand entities, or have a XDocument with entities not expanded?

解决方案

The following worked for me. The key is using reflection to set the value of an internal property 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);
}

阅读全文

相关推荐

最新文章