Why WriteAllText Method Saves XML with special Characters?
When saving the XML string as a file, I get a wrong output XML with special characters. The "<" and ">" tags are replace with <
and >
respectively.
XML String:
<string xmlns="http://smartpark.com/">
<DocumentElement>
<SpaceInfo>
<R_Numb>490</R_Numb>
<FirstName>Michael</FirstName>
<LastName>Jones</LastName>
<Unit>311</Unit>
<Type>RG</Type>
<Location>FLOOR 1</Location>
<Feature>C</Feature>
<Space>100</Space>
<Status>Assigned</Status>
<DateAssigned>2014-09-24T00:00:00-05:00</DateAssigned>
</SpaceInfo>
</DocumentElement>
</string>
Saving Method:
System.IO.File.WriteAllText(Server.MapPath("testing.xml"), urlText,Encoding.UTF8);
Sorry guys here is the entire code snippet:
string url = "http://smartparkllc.com/Service1.asmx/SpaceInfo?space=100"; //store XML returned by webservice string urlText = "";
//call webservice WebRequest request = HttpWebRequest.Create(url); //get response from web service using (WebResponse response = request.GetResponse()) { using (StreamReader reader1 = new StreamReader(response.GetResponseStream())) {
urlText = reader1.ReadToEnd();
testweb.Text = urlText;//this is for testing. Can be remove
//create temp xml files from string containing XML returned by webservice
System.IO.File.WriteAllText(Server.MapPath("testing2.xml"), urlText,Encoding.UTF8);
using (XmlReader reader = XmlReader.Create(Server.MapPath("testing2.xml")))
{
SpaceInfo newspaceinfo = new SpaceInfo();
while (reader.Read())
{
//Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "R_Numb":
if (reader.Read())
{
//get value
newspaceinfo.R_Numb = Convert.ToInt32(reader.Value.Trim());
}
break;
case "FirstName":
if (reader.Read())
{
newspaceinfo.FirstName = reader.Value.Trim();
}
break;
case "LastName":
if (reader.Read())
{
newspaceinfo.LastName = reader.Value.Trim();
}
break;
case "Unit":
if (reader.Read())
{
newspaceinfo.Unit = reader.Value.Trim();
}
break;
case "Type":
if (reader.Read())
{
newspaceinfo.Type = reader.Value.Trim();
}
break;
case "Location":
if (reader.Read())
{
newspaceinfo.Location = reader.Value.Trim();
}
break;
case "Feature":
if (reader.Read())
{
newspaceinfo.Feature = reader.Value.Trim();
}
break;
case "Status":
if (reader.Read())
{
newspaceinfo.Status = reader.Value.Trim();
}
break;
case "DateAssigned":
if (reader.Read())
{
newspaceinfo.DateAssigned = reader.Value.Trim();
}
break;
}
}
}
If you have left and right brackets in your XML anywhere except tags, they will be encoded as <
and >
. This behavior is by design and called escaping. When you read your XML back, those values will be unescaped, and you will see <
and >
again in .NET code.