We help IT Professionals succeed at work.

Is it possible to escape & while loading xml?

ipjyo
ipjyo asked
on
I have an & character in one of the xml nodes as below.

<dependents>9 & 5</dependents>

When I try to load the file as below, it is giving an error  "An error occured while parsing EntityName.". Is it possible to escape this character and load successfully? Thank yu.

m_InputXMLDoc = new XmlDocument();
            if (System.IO.File.Exists(InputFile))
            {
                m_InputXMLDoc.Load(InputFile);
            }

Comment
Watch Question

Most Valuable Expert 2011
Top Expert 2015
Commented:
If you use Linq and XDocument, then you can use the Parse method; if you stick with XmlDocument, then you'll have to escape them (i.e. string replace) before passing the data to XmlDocument.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Hmmm...  you may have mixed results with this. In my testing now, I cannot seem to reproduce the results I witnessed when using the selected solution found here. In the event that you cannot achieve a successful result, my alternate suggestion would be, as previously mentioned, to replace the ampersands before passing to XmlDocument. For example:

XmlDocument m_InputXMLDoc = new XmlDocument();
string xml = System.IO.File.ReadAllText("input.xml");

xml = System.Text.RegularExpressions.Regex.Replace(xml, "&(?!amp;)", "&amp;");
xdoc.LoadXml(m_InputXMLDoc);

Open in new window

Author

Commented:
Thank you very much. I will try this. I may not be able to replace with XDocument since it involves too many code changes.

Thanks again.
Most Valuable Expert 2011
Top Expert 2015
Commented:
If you manage to get XDocument.Parse to work, then you could easily convert it to XmlDocument in this manner:

XDocument xdoc = XDocument.Parse(xml_string);
XmlDocument m_InputXMLDoc = new XmlDocument();

m_InputXMLDoc.Load(xdoc.CreateReader());

Open in new window


Then all you do is put the parse logic ahead of loading the XmlDocument logic. No other changes should be required.

Author

Commented:
Cool. Thanks for your help.