Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I just tried my XElement.Parse solution. I created an extension method on the string class so I can reuse the code easily:</p> <pre><code>public static bool ContainsXHTML(this string input) { try { XElement x = XElement.Parse("&lt;wrapper&gt;" + input + "&lt;/wrapper&gt;"); return !(x.DescendantNodes().Count() == 1 &amp;&amp; x.DescendantNodes().First().NodeType == XmlNodeType.Text); } catch (XmlException ex) { return true; } } </code></pre> <p>One problem I found was that plain text ampersand and less than characters cause an XmlException and indicate that the field contains HTML (which is wrong). To fix this, the input string passed in first needs to have the ampersands and less than characters converted to their equivalent XHTML entities. I wrote another extension method to do that:</p> <pre><code>public static string ConvertXHTMLEntities(this string input) { // Convert all ampersands to the ampersand entity. string output = input; output = output.Replace("&amp;amp;", "amp_token"); output = output.Replace("&amp;", "&amp;amp;"); output = output.Replace("amp_token", "&amp;amp;"); // Convert less than to the less than entity (without messing up tags). output = output.Replace("&lt; ", "&amp;lt; "); return output; } </code></pre> <p>Now I can take a user submitted string and check that it doesn't contain HTML using the following code:</p> <pre><code>bool ContainsHTML = UserEnteredString.ConvertXHTMLEntities().ContainsXHTML(); </code></pre> <p>I'm not sure if this is bullet proof, but I think it's good enough for my situation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload