为什么WriteAllText方法用特殊字符保存XML?
将XML字符串保存为文件时,出现错误的输出XML和特殊字符。 “<”和“>”标签被替换为<
和>
分别。
XML字符串:
<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>
保存方法:
System.IO.File.WriteAllText(Server.MapPath("testing.xml"), urlText,Encoding.UTF8);
对不起,这里的人是整个代码片段:
string url =“http://smartparkllc.com/Service1.asmx/SpaceInfo?space=100”; //存储由webservice返回的XML string urlText =“”;
//调用webservice WebRequest请求= HttpWebRequest.Create(url); //使用(WebRequest response = request.GetResponse()){使用(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;
}
}
}
如果您的XML在标签外的任何地方都有左括号和右括号,则它们将被编码为<
和>
。 这种行为是通过设计并被称为转义。 当你读回你的XML时,这些值将被转义,你将在.NET代码中再次看到<
和>
。
上一篇: Why WriteAllText Method Saves XML with special Characters?