Prevent XmlReader from expanding XML entities

前端 未结 2 1077
说谎
说谎 2021-01-19 07:42

Is there a way to prevent .NET\'s XmlReader class from expanding XML entities into their value when reading the content?

For instance, suppose the follo

2条回答
  •  离开以前
    2021-01-19 08:27

    One way to do that is use `XmlTextReader', like this:

    using (var reader = new XmlTextReader(@"your url"))
    {
        // note this
        reader.EntityHandling = EntityHandling.ExpandCharEntities;
        while (reader.Read())
        {
            // here it will be EntityReference with no exceptions
        }
    }
    

    If that is not an option - you can do the same with XmlReader, but some reflection will be required (at least I don't aware of another way):

    using (var reader = XmlReader.Create(@"your url", new XmlReaderSettings() {
        DtdProcessing = DtdProcessing.Ignore // or Parse
    })) {
         // get internal property which has the same function as above in XmlTextReader
         reader.GetType().GetProperty("EntityHandling", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(reader, EntityHandling.ExpandCharEntities);
         while (reader.Read()) {
              // here it will be EntityReference with no exceptions
         }
     }
    

提交回复
热议问题