ilias
ilias

Reputation: 2682

Read special characters back from XmlDocument in c#

Say I have the an xml with a escaped ampersand (&). How do I then read it back such that the result gives me the 'un-escaped' text.

Running the following gives me "&amp" as the result. How do I get back '&'

void Main()
{
  var xml = @"
  <a>
    &amp;
  </a>
  ";
  var doc = new XmlDocument();
  doc.LoadXml(xml);
  var ele = (XmlElement)doc.FirstChild;
  Console.WriteLine (ele.InnerXml); 
}

Upvotes: 1

Views: 6591

Answers (6)

Tommy Grovnes
Tommy Grovnes

Reputation: 4156

Use ele.InnerText instead of ele.InnerXml

Upvotes: 5

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

The following characters are illegal in XML elements:

Illegal EscapedUsed
------------------
    "   &quot;
    '   &apos;
    <   &lt;
    >   &gt;
    &   &amp;

To get the unescaped value you can use:

 public string UnescapeXMLValue(string xmlValue)
  {
    if (string.IsNullOrEmpty(s)) return s;
   string temp = s;
   temp = temp.Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<").Replace("&amp;", "&");
   return temp ;
 }

To get the escaped value you can use:

public string EscapeXMLValue(string value)
  {
    if (string.IsNullOrEmpty(s)) return s;
   string temp = s;
   temp = temp.Replace("'","&apos;").Replace( "\"", "&quot;").Replace(">","&gt;").Replace( "<","&lt;").Replace( "&","&amp;");
   return temp ;
 }

Upvotes: 0

Vitali Kaspler
Vitali Kaspler

Reputation: 1420

Try using this static method to decode escaped characters: HttpServerUtility.HtmlDecode Method (String) See example here: http://msdn.microsoft.com/ru-ru/library/hwzhtkke.aspx

Upvotes: 0

perilbrain
perilbrain

Reputation: 8207

Console.WriteLine (HttpUtility.UrlDecode(String.Format("{0}",ele.InnerXml)));

Upvotes: 0

Hassan Boutougha
Hassan Boutougha

Reputation: 3919

use
 HttpServerUtility.HtmlDecode (ele.InnerXml);

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

you can use CDATA in order to get your data

Characters like "<" and "&" are illegal in XML elements."<" the parser interprets it as the start of a new element. "&" the parser interprets it as the start of an character entity.

Upvotes: 1

Related Questions