Fork me on GitHub

12/01/2009

[C#] xml 中 url 的 special characters

透過 API 抓取的 xml 欄位中若有網址的資料,當中會有 escape 字元,須經過處理將這些 escape 字元去除

public static string EscapeXml( this string s )
{
string xml = s;
if ( !string.IsNullOrEmpty( xml ) )
{
// replace literal values with entities
xml = xml.Replace( "&", "&" );
xml = xml.Replace( "<", "<" );
xml = xml.Replace( ">", ">" );
xml = xml.Replace( "\"", """ );
xml = xml.Replace( "'", "'" );
}
return xml;
}

public static string UnescapeXml( this string s )
{
string unxml = s;
if ( !string.IsNullOrEmpty( unxml ) )
{
// replace entities with literal values
unxml = unxml.Replace( "'", "'" );
unxml = unxml.Replace( """, "\"" );
unxml = unxml.Replace( ">", ">" );
unxml = unxml.Replace( "<", "<" );
unxml = unxml.Replace( "&", "&" );
}
return unxml;
}

參考資料: http://www.csharper.net/blog/escape_xml_string_characters_in_c_.aspx

No comments:

Post a Comment