【问题标题】:C# XmlDocument.LoadXml(string) failure (NotSupportedException) [duplicate]C# XmlDocument.LoadXml(string) 失败 (NotSupportedException) [重复]
【发布时间】:2018-02-05 17:33:51
【问题描述】:

尝试将字符串值加载到 C# 中的 XML 文档中。直到最近,这段代码一直运行良好。我不知道为什么它现在失败了......

strJournalReturn = ServiceConnect.PostInventoryJournal(userName, password, 
type, effectiveDate, fromWarehouse, toWarehouse, department, project, asset, 
workOrder, jobNumber, reason, lTransactions);

    if (!strJournalReturn.Contains("INTERNALERROR"))
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(strJournalReturn);
        }

strJournalReturn 的值为...

"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<JOURNAL-
SERVICE>\n<ERROR>1</ERROR>\n<ERRORMESSAGES>\n<ERRORMESSAGE>DEPARTMENT is 
required for direct issues & reserves with 
backorders</ERRORMESSAGE>\n</ERRORMESSAGES>\n</JOURNAL-SERVICE>"

这会引发异常“NotSupportedException”。任何想法/想法将不胜感激。

如果这篇文章的细节不够,我提前道歉,因为这是我第一次在这里发帖。

【问题讨论】:

  • @RyanWilson 我不认为这是关于 xml 中的错误,而是尝试将 xml 加载到 XmlDocument 中的错误。
  • 这是我期望在这种情况下得到的错误。但是,当尝试将该 XML 字符串加载到 XmlDocument 中时,它会出现“NotSupportedException”。我认为 XML 的格式不正确,但我没有发现任何问题。
  • 字符串内容的 xml 编码不正确。例如&
  • 您可能需要考虑改用 Linq-to-Xml DOM。
  • 仅供参考,拥有这么多参数的方法被认为是反模式。 Code Complete,第 2 版 (McConnell),第 178 页:“将例程的参数数量限制为大约 7。7 是人们理解的神奇数字。研究发现,人们通常无法跟踪一次超过七块信息...如果您发现自己始终传递多个参数,则说明您的例程之间的耦合太紧了。设计例程或例程组以减少耦合。”

标签: c# xml


【解决方案1】:

您要解析的字符串包含无效字符,例如&符号。(&amp;

DEPARTMENT is required for direct issues & reserves with backorders

通常,xml 应该被正确编码。在尝试解析它之前,可以选择使用Replace

var str = "<JOURNAL-SERVICE><ERROR>1</ERROR><ERRORMESSAGES>" +
            "<ERRORMESSAGE>DEPARTMENT is required for direct issues & reserves with backorders</ERRORMESSAGE>" +
            "</ERRORMESSAGES></JOURNAL-SERVICE>";
str = str.Replace("&", "&amp;");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(str);

但是,请确保其他非编码字符可能包含在 xml 中。

【讨论】:

    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2019-01-25
    • 1970-01-01
    • 2010-12-18
    • 2012-09-27
    • 2020-07-14
    相关资源
    最近更新 更多