Prevent XmlTextReader Extension

I am trying to read an XML document without an entity extension, do some manipulations with it, and re-save it with unexpanded objects since they were originally.

When using XDocument directly, it does not load, throwing an exception, tell me that it has unexpanded objects:

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 constructor to the XDocument constructor, but the EntityHandling property has no "no expand" extension:

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

In addition, I looked at the XmlReader.Create function, but MSDN says: "Readers created with the Create method extend all entities."

How can I create an XmlReader that does not extend entities, or does not have an XDocument with entities?

+7
xml linq-to-xml entity xmlreader
source share
2 answers

The following worked for me. The key uses reflection to set the value of the internal DisableUndeclaredEntityCheck property.

 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); } 
+3
source share

decasteljau! The funny thing is that I found your message how to solve my problem. And my problem was related to the case when entities are not resolved at all. So thanks for the answer for my question. And the following 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();

-3
source share

All Articles