Soner
Soner

Reputation: 115

Xml syntax error with literal ampersand & character

I have method in order to replace xml

Replace method:

public string EscapeXMLValue(string xmlString)
{
            if (xmlString == null)
                throw new ArgumentNullException("xmlString");

            return xmlString.Replace("&", "&");
}

This is my code and I get an exception:

I have xml and try to parse after that I want to use .LoadXml

  XML = EscapeXMLValue(XML); // Parse & here

  xmlDoc.LoadXml(XML); // I get error here

XML:

<Vehicle>HB ICON 1.5 DCI 90 S&amp;S</Vehicle>

Error:

An error occurred while parsing EntityName. Line 22503, position 40.

If I replace &amp; with &, it works, however if I replace & with &amp; it displays exception.

How can I solve the problem for &amp;? How can I remove it or do anything?

Upvotes: 0

Views: 1133

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

Well-formed XML can't contain an unescaped & character except as part of an entity reference. When you replace &amp; by &, you achieve nothing other than making your XML ill-formed. So surely the simple answer is, don't do it.

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31576

How can I solve the problem for &?

Put it into a CDATA section to inform the Xml compiler that it is treated as a literal

 <Vehicle><![CDATA[HB ICON 1.5 DCI 90 S&amp;S]]></Vehicle>

Upvotes: 0

Related Questions