本周使用cell表结合xmlhttp组件开发异步多行数据插入操作,遇到数据为&时发生xml解析错误
Reflector和google后发现
是由于特殊字符造成,需要进行处理:
<转化成<
>转化成>
‘转化成'
“转化成"
&转化成&
在W3C的技术规范中,也可以看到这样的字符不允许出现:
http://www.w3.org/TR/2001/REC-xml-c14n-20010315
于是找了一个javascript的htmlEncode函数:
HTMLEncode = function( text )
{
if ( typeof( text ) != "string" )
text = text.toString() ;
text = text.replace(
/&/g, "&").replace(
/"/g, """).replace(
/</g, "<").replace(
/>/g, ">") ;
return text ;
}
{
if ( typeof( text ) != "string" )
text = text.toString() ;
text = text.replace(
/&/g, "&").replace(
/"/g, """).replace(
/</g, "<").replace(
/>/g, ">") ;
return text ;
}
问题解决,使用时:
前台js拼凑xml string:
function GetString(iRow)
{
s1 = HTMLEncode(form1.DCellWeb1.GetCellString(2,iCurrentRow,0));
s2 = HTMLEncode(form1.DCellWeb1.GetCellString(3,iCurrentRow,0));
s3 = HTMLEncode(form1.DCellWeb1.GetCellString(4,iCurrentRow,0));
s4 = HTMLEncode(form1.DCellWeb1.GetCellString(5,iCurrentRow,0));
return "<xml version='1.0' encoding='GB2312'><data>"+
"<s1>"+s1+"</s1>" +
"<s2>"+s2+"</s2>" +
"<s3>"+s3+"</s3>" +
"<s4>"+s4+"</s4>" +
"</data></xml>"
}
{
s1 = HTMLEncode(form1.DCellWeb1.GetCellString(2,iCurrentRow,0));
s2 = HTMLEncode(form1.DCellWeb1.GetCellString(3,iCurrentRow,0));
s3 = HTMLEncode(form1.DCellWeb1.GetCellString(4,iCurrentRow,0));
s4 = HTMLEncode(form1.DCellWeb1.GetCellString(5,iCurrentRow,0));
return "<xml version='1.0' encoding='GB2312'><data>"+
"<s1>"+s1+"</s1>" +
"<s2>"+s2+"</s2>" +
"<s3>"+s3+"</s3>" +
"<s4>"+s4+"</s4>" +
"</data></xml>"
}
后台c#解析:
string sProjCode, sProjName, sUnitName, sManager, sDirectionCode;
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(Request.InputStream);
sProjCode = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s1")[0].InnerText.Trim());
sProjName = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s2")[0].InnerText.Trim());
sUnitName = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s3")[0].InnerText.Trim());
sManager = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s4")[0].InnerText.Trim());
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(Request.InputStream);
sProjCode = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s1")[0].InnerText.Trim());
sProjName = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s2")[0].InnerText.Trim());
sUnitName = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s3")[0].InnerText.Trim());
sManager = HttpUtility.HtmlDecode(xDoc.GetElementsByTagName("s4")[0].InnerText.Trim());