Search code examples
c#.netxml.net-2.0c#-2.0

Escaping ONLY contents of Node in XML


I have a part of code mentioned like below.

    //Reading from a file and assign to the variable named "s"
    string s = "<item><name> Foo </name></item>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(s);

But, it stops working if the contents has characters something like "<", ">"..etc.

string s = "<item><name> Foo > Bar </name></item>";

I know, I have to escape those characters before loading but, if I do like

 doc.LoadXml(System.Security.SecurityElement.Escape(s));

, the tags (< , >) are also escaped and as a result, the error occurs.

How can I solve this problem?


Solution

  • a tricky solution:

        string s = "<item><name> Foo > Bar </name></item>";
        s = Regex.Replace(s, @"<[^>]+?>", m => HttpUtility.HtmlEncode(m.Value)).Replace("<","ojlovecd").Replace(">","cdloveoj");
        s = HttpUtility.HtmlDecode(s).Replace("ojlovecd", "&gt;").Replace("cdloveoj", "&lt;");
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(s);