Xml Load error - Reference to undeclared entity

test code 1 Reputation point
2020-10-13T06:38:11.443+00:00

I am using below vb.net code to load xml file.

Dim reader As XmlTextReader = New XmlTextReader("D:\file_1.xml")    
   reader.EntityHandling = EntityHandling.ExpandEntities            
   Dim xDoc As XmlDocument = New XmlDocument()          
   xDoc.Load(reader)   

xdoc.load() will give "reference to undeclared entity"
The Input xml file have List of Special character.

Like:<_1 Value="Á"/>
<_2 Value="Â"/>
<_3 Value="â"/>
<_4 Value="´"/>
<_5 Value="Æ"/>

This error can be solved by declaring the entity in the xml file.

<!DOCTYPE doctypeName [
   <!ENTITY Aacute "&#193;">
]> 

Is there any method to load the xml without changing xml using vb.net code?

Developer technologies Windows Forms
{count} votes

2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2020-10-13T08:32:53.63+00:00

    Hi test code,
    Xml doesn't define entities (ie named references to UNICODE characters), so &Acirc, &AElig are not translated to their corresponding character. You need to use the numerical value instead.
    Here is a similar thread you can refer to.


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Viorel 122.6K Reputation points
    2020-10-13T08:53:37.797+00:00

    If you cannot modify the original file, then maybe create dynamically a helper file that includes the entity definition and a reference to original file. Something like this:

    Dim filename = "D:\file_1.xml"
    Dim t = Path.GetTempFileName
    
    File.WriteAllText(t, $"<?xml version='1.0' encoding='utf-8' ?>
    <!DOCTYPE xml [
      <!ENTITY Aacute '&#193;'>
      <!-- TODO: add more entities -->
      <!ENTITY otherFile SYSTEM 'file://{filename}'>
    ]>
    <xml>
      &otherFile;
    </xml>")
    
    Dim xDoc As XmlDocument = New XmlDocument()
    
    Using reader As XmlTextReader = New XmlTextReader(t)
       reader.EntityHandling = EntityHandling.ExpandEntities
       reader.XmlResolver = New XmlUrlResolver
       xDoc.Load(reader)
    End Using
    
    File.Delete(t)
    
    Console.WriteLine(xDoc.OuterXml)
    

    However the loaded document contain a different root node (<xml>).

    Use this workaround if it is difficult to find a solution based on some custom entity resolver.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.