读书人

过虑xml 非法字符,该怎么解决

发布时间: 2011-12-31 23:50:30 作者: rapoo

过虑xml 非法字符
再解析 xml 文件时,由于其中包含16进制的非法字符而出错
即使是包含在 <![CDATA[ 内容 ]]> 中也会出错


当前的解决方法是出现在一个替换一个

content = content.Replace( " ", " ");
content = content.Replace( "­ ", " ");
content = content.Replace( "• ", " ");

求一个过虑全部非法字符的方法:

[解决办法]
一共有5个!
字符 HTML字符 字符编码
和(and) & & &
单引号 ' ' '
双引号 " " "
大于号 > > >
小于号 < < <

[解决办法]
如果有非法的字符则以认为XML格式不正确而不处理;

在生成Xml的时候使用正确的途径来编写,比如使用XmlWriter或XmlDocument等,从而可以一定程序上避免非法字符.
[解决办法]
从而可以一定程序上避免非法字符是正确做法。

字符 HTML字符 字符编码
和(and) & & &
单引号 ' ' '
双引号 " " "
大于号 > > >
小于号 < < <
[解决办法]
我最近也在弄这个.顺利弄了一个方法.
希望可以帮到楼主

C# code
public static string FullHTMLEncode(string inputVal)    {        if (inputVal != null)        {            inputVal = inputVal.Replace(">", ">");            inputVal = inputVal.Replace("<", "<");            inputVal = inputVal.Replace("\'", "'");            inputVal = inputVal.Replace("\"", """);            inputVal = inputVal.Replace(string.Format("{0}", (char)32), " ");            inputVal = inputVal.Replace(string.Format("{0}", (char)9), " ");            inputVal = inputVal.Replace(string.Format("{0}", (char)34), """);            inputVal = inputVal.Replace(string.Format("{0}", (char)39), "'");            inputVal = inputVal.Replace(string.Format("{0}", (char)13), "");                    }        return inputVal;    }
[解决办法]
解决方法,节点内容编码。

1)base64编码形式存放
2)html代码转成unicode编码存放(这个说明可能有误)


这个的转码函数的vbs写法是
Function uni(Chinese)
dim j,a
For j = 1 to Len (Chinese)
a=Mid(Chinese, j, 1)
uni= uni & "&#x" & Hex(Ascw(a)) & ";"
next
End Function

读书人网 >asp.net

热点推荐