Prevent XmlTextReader from expanding entities

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?

Answers


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);
}

decasteljau! The funny thing that I found your post searching how to solve my problem. And my problem was related to case when entities are not resolved at all. So thank you for answer for my question. And the following is answer to your question: please, use XmlDocument.

XDocument document = XDocument.Load("test.xml"); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(Console.Out, settings)) { document.WriteTo(writer); } Console.WriteLine();


Need Your Help

Ads are not served to my app even After integrating with MoPub

android admob adsense google-play mopub

I have created an account in Mopub and integarted neccessary code to my android app to display a banner ad. After that Demo MoPub ad started displayed.