Not able to display XML in WordPress post

If you want to display an XML fragment in a WordPress post – how do you do that?

Suppose you want to display this:

Read More
<family>
    <dad>whatever</dad>
    <mom>whatever</mom>
</family>

Using the [sourcecode language="xml"] does not help, as it mangles up the XML.
Also, I believe, plugins cannot be used with free version of WordPress ( i.e wordpress.com ) – so, probably that won’t be an option.

Using HTML <pre> tag works, but it does not give correct look and feel.
Can any one show me how they have done it?

Related posts

Leave a Reply

4 comments

  1. The wordpress codex has a whole page about writing code in your posts.

    http://codex.wordpress.org/Writing_Code_in_Your_Posts

    Their suggestion is to use html entity codes within <pre> or <code> tags

    &lt;family&gt;
        &lt;dad&gt;whatever&lt;/dad&gt;
        &lt;mom&gt;whatever&lt;/mom&gt;
    &lt;/family&gt;
    

    This could be tedious if you have a lot of code to show in your post. I suggest writing a small shortcode that would do this for you.

    <?php
    function xml_shortcode( $atts, $content ) {
        return '<pre>' . htmlentities( $content ) . '</pre>';
    }
    
    add_shortcode( 'xml', `xml_shortcode` );
    ?>
    

    How to use your shortcode in a post

    [xml]your code here[/xml]
    
  2. If [sourcecode] is available but you cannot install additional plugins or add shortcodes (which is the case on wordpress.com), you have, to my knowledge, no other option than to encode the problematic characters before copying them.

    Here are the detailed steps:

    1. Encode your snippet using an HTML encode, for instance using a free, online encoder
    2. edit your post in HTML mode
    3. add [sourcecode language=”xml”]
    4. past the encoded source code
    5. add [/sourcecode]
  3. I suffered from this problem recently.
    For me what worked was to enter the code in text mode. Selection of code. Application of code formatting from the Format menu.

    Later, I used the crayon syntax highlight plugin. The plugin works well, you have to follow the same process as above with the only difference that instead of code formatting option, choose the crayon option after selecting the code to highlight.

    You can check the highlighting here

  4. WordPress.com now has built-in support for code highlighting in a variety of languages using the [code] shortcode. I find that I still have to use html entity codes when highlighting XML, but other languages work well (JavaScript, C#, etc.), and it looks much better to the reader than your basic <pre> or <code> tags.