3
votes

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>
1
You need to set XmlReaderSettings.XmlResolver 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? and How to prevent XXE attack ( XmlDocument in .net). - dbc
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
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 and Customizing the XmlUrlResolver Class. - dbc
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
XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = CredentialCache.DefaultCredentials; settings.XmlResolver = resolver; - blue_jack

1 Answers

2
votes

I added this to the settings.

  XmlUrlResolver resolver = new XmlUrlResolver();
    resolver.Credentials = CredentialCache.DefaultCredentials;
    settings.XmlResolver = resolver;