简体   繁体   中英

XmlDocument throwing “An error occurred while parsing EntityName”

I have a function where I am passing a string as params called filterXML which contains '&' in one of the properties.

I know that XML will not recognize it and it will throw me an err. Here is my code:

 public XmlDocument TestXMLDoc(string filterXml)
{
    XmlDocument doc = new XmlDocument();
    XmlNode root = doc.CreateElement("ResponseItems");

    // put that root into our document (which is an empty placeholder now)
    doc.AppendChild(root);

    try
    {
        XmlDocument docFilter = new XmlDocument();
        docFilter.PreserveWhitespace = true;

        if (string.IsNullOrEmpty(filterXml) == false)
            docFilter.LoadXml(filterXml); //ERROR THROWN HERE!!!

What should I change in my code to edit or parse filterXml? My filterXml looks like this:

<Testing>
<Test>CITY & COUNTY</Test>
</Testing>

I am changing my string value from & to &. Here is my code for that:

string editXml = filterXml;
    if (editXml.Contains("&"))
    {
        editXml.Replace('&', '&amp;');
    }

But its giving me an err on inside the if statement : Too many literals.

The file shown above is not well-formed XML because the ampersand is not escaped.

You can try with:

<Testing>
  <Test>CITY &amp; COUNTY</Test>
</Testing>

or:

<Testing>
  <Test><![CDATA[CITY & COUNTY]]></Test>
</Testing>

About the second question: there are two signatures for String.Replace. One that takes characters, the other that takes strings. Using single quotes attempts to build character literals - but "&amp;", for C#, is really a string (it has five characters).

Does it work with double quotes?

editXml.Replace("&", "&amp;");

If you would like to be a bit more conservative, you could also write code to ensure that the &s you are replacing are not followed by one of

amp; quot; apos; gt; lt; or #

(but this would still not be a perfect filtering)

To specify an ampersand in XML you should use &amp; since the ampersand sign ('&') has a special meaning in XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM