如何解决XML字符串中无效的字符
| 我从第三方收到一个xml字符串。 xml字符串包含无效字符,例如&和\'。我试图将其放在数据集(ASP.NET)中。它引发错误。任何人都可以帮忙。解决方法
告诉/询问第三方以提供有效的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;
}
,使用xml导出数据的最佳方法是
<![CDATA[Your data goes here.]]>
但是,当您使用第三方xml时,请尝试使用此帖子,以便处理xml中的特殊字符。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。