How to preserve raw XML / HTML and its formatting inside of a PRE-tag

admin

Administrator
Staff member
When I choose "<strong>View page source</strong>" on a certain blog post of my site, I see the correct result:

Code:
&lt;variable name="myPublicVar" type="String"&gt;
  &lt;metadata name="MemberMetaExamplePublic" /&gt;
&lt;/variable&gt;
&lt;accessor name="myAccessor" access="readwrite" type="Boolean" declaredBy="MetadataTest"&gt;
  &lt;metadata name="MemberMetaExampleGetter" /&gt;
&lt;/accessor&gt;
&lt;method name="myMethod" declaredBy="MetadataTest" returnType="void"&gt;
  &lt;metadata name="MemberMetaExampleMethod" /&gt;
&lt;/method&gt;
&lt;metadata name="CustomMeta"&gt;
  &lt;arg key="param1" value="foo" /&gt;
  &lt;arg key="param2" value="bar "/&gt;
&lt;/metadata&gt;

But when I use jQuery to replace each '&lt;' and '>' to '&amp;lt;' and '&amp;gt;' respectively, the rendered result by the browser (in Chrome) messes up the self-closing elements:

Code:
&lt;variable name="myPublicVar" type="String"&gt;
  &lt;metadata name="MemberMetaExamplePublic"&gt;
&lt;/metadata&gt;&lt;/variable&gt;
&lt;accessor name="myAccessor" access="readwrite" type="Boolean" declaredby="MetadataTest"&gt;
  &lt;metadata name="MemberMetaExampleGetter"&gt;
&lt;/metadata&gt;&lt;/accessor&gt;
&lt;method name="myMethod" declaredby="MetadataTest" returntype="void"&gt;
  &lt;metadata name="MemberMetaExampleMethod"&gt;
&lt;/metadata&gt;&lt;/method&gt;
&lt;metadata name="CustomMeta"&gt;
  &lt;arg key="param1" value="foo"&gt;
  &lt;arg key="param2" value="bar "&gt;
&lt;/arg&gt;&lt;/arg&gt;&lt;/metadata&gt;

Notice how the
Code:
&lt;metadata&gt;
elements unnecessarily generates a closing tag, and how the two
Code:
&lt;arg&gt;
elements in the last one incorrectly generates closing tags that are actually wrapping up one
Code:
&lt;arg&gt;
into another
Code:
&lt;arg&gt;
.

The conversion I use happens in this section of jQuery / JavaScript code:

Code:
$('pre.raw').each( function(pIndex, pDIV) {
  pDIV.innerHTML = pDIV.innerHTML.replace(/\&lt;/g, "&amp;lt;").replace(/\&gt;/g, "&amp;gt;");
});

What could be done to stop the code from being parsed? I'm not certain whether the browser is to blame, jQuery or JavaScript?

<em>NOTE: Although I was having this problem in Wordpress and I could ask this in the
Code:
wordpress.stackexchange.com
site, I think this is a generic problem that can be found in various web development scenarios.</em>