Richard
Richard

Reputation: 101

How can I write raw XML to a Label in ASP.NET

I am getting a block of XML back from a web service. The client wants to see this raw XML in a label on the page. When I try this:

lblXmlReturned.Text = returnedXml;

only the text gets displayed, without any of the XML tags. I need to include everything that gets returned from the web service.

This is a trimmed down sample of the XML being returned:

<Result Matches="1">
    <VehicleData>
        <Make>Volkswagen</Make>
        <UK_History>false</UK_History>
    </VehicleData>
    <ABI>
        <ABI_Code></ABI_Code>
        <Advisory_Insurance_Group></Advisory_Insurance_Group>
    </ABI>
    <Risk_Indicators>       
        <Change_In_Colour>false</Change_In_Colour>
    </Risk_Indicators>
    <Valuation>
        <Value xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></Value>
    </Valuation>
    <NCAP>
        <Pre_2009></Pre_2009>
    </NCAP>
</Result>

What can I do to make this appear on the screen? I noticed that Stack Overflow does a pretty good job of putting the XML on the scren. I checked the source and it's using <pre> tags. Is this something that I have have to use?

Upvotes: 10

Views: 5457

Answers (2)

Dan Diplo
Dan Diplo

Reputation: 25359

You need to HtmlEncode the XML first (which escapes special characters like < and > ):

string encodedXml = HttpUtility.HtmlEncode(xml);
Label1.Text = encodedXml;

Surrounding it in PRE tags would help preserve formatting, so you could do:

string encodedXml = String.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(xml));
Label1.Text = encodedXml;

As Bala R mentions, you could just use a Literal control with Mode="Encode" as this automatically HtmlEncodes any string. However, this would also encode any PRE tags you added into the string, which you wouldn't want. You could also use white-space:pre in CSS which should do the same thing as the PRE tag, I think.

Upvotes: 8

Bala R
Bala R

Reputation: 109007

It would be easier to use a <asp:Literal /> with it's Mode set to Encode than to deal with manually encoding Label's Text

<asp:Literal runat="server" ID="Literal1"  Mode="Encode" />

Upvotes: 14

Related Questions