XML字符串中的字符无效

本文关键字:字符 无效 字符串 XML | 更新日期: 2023-09-27 17:57:40

我从第三方收到一个xml字符串。xml字符串包含无效字符,如&和'。我正试图把它放在数据集中(ASP.NET)。它抛出错误。有人能帮忙吗。

XML字符串中的字符无效

告诉/要求第三方提供有效的XML。

如果互操作性标准没有得到遵守,它们就没有多大意义。如果它们今天传递给你的是无效字符,那么如何阻止它们明天传递不匹配的节点呢?或者根本没有标签?

如果没有标准,那么您可能需要对无数场景进行编码。

也就是说,你可以:

  • 请确保您的代码中没有问题(如果需要详细信息,请发布代码)
  • 创建一个已知查找/替换场景的可配置列表,并预处理输入的"XML"字符串
  • 如果数据完整性不重要(就我个人而言,我认为它总是重要的),您可以将数据加载到HTML解析器中,这将更加宽容,并允许类似XMLDOM的文档访问

根据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>( "&", "&amp;" ) );
    replacements.Add( new Tuple<string, string>( "'"", "&quot;" ) );
    replacements.Add( new Tuple<string, string>( "''", "&apos;" ) );
    foreach( var replacement in replacements )
    {
        xml = xml .Replace( replacement.Item1, replacement.Item2 );
    }
     return xml;
}

使用xml导出数据的最佳方式是

<![CDATA[Your data goes here.]]>

但由于您使用的是第三方xml,请尝试使用此帖子来处理xml中的特殊字符。