Preserve newline characters in xml asp.net

While using a telerik text box in asp.net in multiline mode, I faced a weird issue where pressing enter was adding spaces and not new line. So, to fix that, I had to use the below css to add new line characters:

div.divTxtBox .txtBoxNewLineFix {
    width: 100% !important;
    white-space: pre !important;
}

RadTextBox aspx code:

<telerik:RadTextBox ID="txtDev"
	Wrap="true" TextMode="MultiLine" runat="server" Width="98%" CssClass="txtBoxNewLineFix" Rows="8">
</telerik:RadTextBox>

Also, while saving the text to the SQL Server database, since I was creating the XML in a C# string, the new line characters were getting replaced with new lines in the XML but it did not replicate in the saved text, so I had to preserve the \r\n characters as below:

private string preserveNewLine(string str)
{
	string sReturnValue;
	sReturnValue = str.Replace("\r\n", "
");

	return sReturnValue;
}

The below xml sample is prepared using StringBuilder in C#:

StringBuilder PlanData = new StringBuilder();
PlanData.AppendLine("<?xml version=\"1.0\" standalone=\"yes\" ?>");
PlanData.Append("<XMLInfo ");
PlanData.Append(" UserDataId=" + "\"" + UserDataId + "\"");
PlanData.Append(" UpdatedBy=" + "\"" + objUser.UserID + "\"");
PlanData.Append(" UpdatedOn=" + "\"" + DateTime.Now.ToString() + "\"");
PlanData.AppendLine(">");
PlanData.AppendLine("<Plans>");

//TO DO loop through data with following lines to add multiple Plan child elements:
Comments = preserveNewLine(Comments);
PlanData.AppendLine("<Plan ID=" + "\"" + ID + "\"" + " Comment=" + "\"" + Comments + "\"" + "/>");

PlanData.AppendLine("</Plans>");
PlanData.AppendLine("</XMLInfo>");

C# sample debug output with new lines converted:

{<?xml version="1.0" standalone="yes" ?>
<XMLInfo  UserDataId="7180" UpdatedBy="1898" UpdatedOn="10/10/2019 6:14:00 PM">
<Plans>
<Plan ID="38685" Comment="1 1111 11111 111111 1111111 11111111 1111   111111

test new line"/>
<Plan ID="38686" Comment="11  2222  2222222    222222      444"/>
}

C# sample debug output with new lines characters preserved:

{<?xml version="1.0" standalone="yes" ?>
<XMLInfo  UserDataId="7180" UpdatedBy="1898" UpdatedOn="10/10/2019 6:39:55 PM">
<Plans>
<Plan ID="38685" Comment="1 1111 11111 111111 1111111 11111111 1111   111111    

test new line"/>
}

So when this xml is saved to SQL Server and pulled back in the Text Box, the new lines will show up correctly.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.