3

I created an XML document named test1.xml that links to external dtd mydtd2.dtd which has an entity circ defined. Both files are saved in same folder. But when reading the XML file with XmlReader I get error Reference to undeclared entity circ.

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE test1 SYSTEM "mydtd2.dtd">
 <test1> 
   print this character &circ; 
</test1>

<!ELEMENT test1 >
<!ENTITY circ "&#x0005E;">



 XmlReaderSettings settings = new XmlReaderSettings();
 settings.DtdProcessing = DtdProcessing.Parse;
 settings.CheckCharacters = false;
 XmlDocument doc = new XmlDocument();

 using (XmlReader reader = XmlReader.Create(filename, settings))
 {
    doc.Load(reader);
 }

When I add the entity to the top of the XML file internally it works.

<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE wow [
  <!ENTITY circ     "&#x0005E;" >
]>

<test1> 
     wow can this work ( j &circ;y )
</test1>
blue_jack
  • 61
  • 3
  • You need to set [`XmlReaderSettings.XmlResolver`](https://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver(v=vs.110).aspx) **but there are security risks in doing this** since you might end up loading something malicious from an external site. To get started you might look at [How do I resolve entities when loading into an XDocument?](https://stackoverflow.com/q/1645767/3744182) and [How to prevent XXE attack ( XmlDocument in .net)](https://stackoverflow.com/q/14230988/3744182). – dbc Jan 08 '18 at 20:32
  • I don't need to load a public URI for my external DTD. I have my own private DTD that I have in the same folder as the XML document. – blue_jack Jan 08 '18 at 21:52
  • Hmmm I can't find an existing answer that shows that. You might start with [Resolving the Unknown: Building Custom XmlResolvers in the .NET Framework](https://msdn.microsoft.com/en-us/library/aa302284.aspx) and [Customizing the XmlUrlResolver Class](https://msdn.microsoft.com/en-us/library/bb669135(v=vs.100).aspx). – dbc Jan 09 '18 at 01:00
  • I got it to work using XmlResolver I just used the default settings and just by having it created in the setings the DTD document got pulled in and the XML doc can now find it. – blue_jack Jan 09 '18 at 15:41
  • XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = CredentialCache.DefaultCredentials; settings.XmlResolver = resolver; – blue_jack Jan 09 '18 at 15:41

1 Answers1

2

I added this to the settings.

  XmlUrlResolver resolver = new XmlUrlResolver();
    resolver.Credentials = CredentialCache.DefaultCredentials;
    settings.XmlResolver = resolver;
blue_jack
  • 61
  • 3
  • Yep, appears to work excellently. Not really clear from the MSDN documentation. You should accept your own answer :). – Abel Feb 27 '19 at 14:00