我收到來自第三方的xml字符串。 xml字符串包含無效字符,如&和'。我試圖把它放在數據集(ASP.NET)中。它會拋出錯誤。任何人都可以請求幫助。來自XML字符串的無效字符
回答
告訴/請求第三方提供有效的XML。
當不遵守互操作性標準時,互操作性標準不算太多。如果他們今天向你傳遞了無效字符,那麼明天要阻止它們傳遞不匹配的節點呢?或根本沒有標籤?
如果沒有標準,那麼您可能需要編碼的情景數量無窮無盡。
這就是說,你可以:
- 確保它不是一個問題,在您的代碼(郵編,如果你想細節)。
- 創建已知查找/替換方案的可配置列表,並預處理輸入的「XML」字符串。
- 如果數據完整性不重要(我個人認爲它總是如此),那麼您可以將數據加載到HTML解析器中,這將更加寬容並允許XML DOM類文檔訪問。
根據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;
}
嘗試System.Security.SecurityElement.Escape(xmlString);它刪除了「<" and ">」的xml節點也..有沒有解決它..謝謝.. – srikanth 2011-05-25 06:45:48
@srikanth - System.SecurityElement.Escape記錄執行5個字符替換:http://msdn.microsoft.com /en-us/library/system.security.securityelement.escape(v=VS.100).aspx。手動爲您需要的3個字符串替換,並省略兩個轉義標記字符。 – 2011-05-25 07:22:41
+1最重要的是:要求第三方提供格式良好的XML - 其他一切都是不可接受的。 – oleschri 2011-05-25 09:35:18
什麼是錯誤? – 2011-05-25 04:24:14
xml string中的字符無效.. <?xml version =「1.0」standalone =「yes」?> 。公司名稱有無效字符和 BLAUS 布勞爾見Delikatessen公司名稱> 漢娜穆斯聯繫人姓名> 測試 SPLIR 分離軌啤酒與麥芽公司名稱> Art raunschweiger ContactName> WY –
srikanth
2011-05-25 05:28:03