[英]Invalid Characters from XML string
我從第三方收到一個 xml 字符串。 xml 字符串包含無效字符,如 & 和 '。 我正在嘗試將其放入數據集(ASP.NET)中。 它拋出錯誤。 任何人都可以幫忙。
告訴/要求第三方提供有效的 XML。
如果不遵守互操作性標准,它們就沒有多大意義。 如果他們今天向您傳遞無效字符,那么明天如何阻止他們傳遞不匹配的節點? 還是根本沒有標簽?
如果沒有標准,那么您可能需要編寫無數的場景。
也就是說,您可以:
根據 OP 的評論,這是一個非常非常簡單的可配置查找/替換示例。
public string PreProcessXml( string xml )
{
// this list could be read from a config file
List<Tuple<string, string>> replacements = new List<Tuple<string, string>>();
// Important: if there are VALID uses of an ampersand in your document,
// this may invalidate them! Perform a more elaborate check using a
// regex, or ensure that there are no valid entities already in the document.
replacements.Add( new Tuple<string, string>( "&", "&" ) );
replacements.Add( new Tuple<string, string>( "\"", """ ) );
replacements.Add( new Tuple<string, string>( "\'", "'" ) );
foreach( var replacement in replacements )
{
xml = xml .Replace( replacement.Item1, replacement.Item2 );
}
return xml;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.