【问题标题】:Root element is missing when load XmlDocument from a stream从流中加载 XmlDocument 时缺少根元素
【发布时间】:2011-07-05 14:13:58
【问题描述】:

我有以下代码:

var XmlDoc = new XmlDocument();
Console.WriteLine();
Console.WriteLine(response.ReadToEnd());
Console.WriteLine();

// setup the XML namespace manager
XmlNamespaceManager mgr = new XmlNamespaceManager(XmlDoc.NameTable);
// add the relevant namespaces to the XML namespace manager
mgr.AddNamespace("ns", "http://triblue.com/SeriousPayments/");
XmlDoc.LoadXml(response.ReadToEnd());
XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response", mgr);

while (NodePath != null)
  {
      foreach (XmlNode Xml_Node in NodePath)
      {
          Console.WriteLine(Xml_Node.Name + " " + Xml_Node.InnerText);
      }
  }

我得到:

缺少根元素。

在:

XmlDoc.LoadXml(response.ReadToEnd());

我的 XML 如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://triblue.com/SeriousPayments/">
    <Result>0</Result>
    <Message>Pending</Message>
    <PNRef>230828</PNRef>
    <ExtData>InvNum=786</ExtData>
</Response>

我迷路了。有人可以告诉我我做错了什么吗?我知道我之前有这个工作,所以我不确定我搞砸了什么。

一如既往,谢谢!

* 得到答案后我的编辑原因**

我需要换行:

XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response");

到:

XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response", mgr);

没有它,这将无法工作。

【问题讨论】:

  • 什么是 Console.WriteLine(response.ReadToEnd());输出?
  • 您如何期望来自 steam 的任何“实质性”内容? :-) (对不起,无法抗拒......)

标签: c# .net xml exception-handling


【解决方案1】:

您似乎在阅读response 流两次。那样不行,你第二次得到一个空字符串。删除Console.WriteLine(response.ReadToEnd()); 行或将响应保存到字符串:

string responseString = response.ReadToEnd();
…
Console.WriteLine(reponseString);
…
XmlDoc.LoadXml(responseString);

【讨论】:

  • 比我快 24 秒,我想我必须提高我的打字速度 :)
  • 太棒了!泰!这让我越过了那条线!我现在在 nodepath 行得到这个:需要命名空间管理器或 XsltContext。此查询具有前缀、变量或用户定义的函数。
  • @ErocM,cmets 不适合提问或回答问题。你应该问一个全新的问题。
  • 不错!这帮助我在 using 语句中通过 StreamReader 类的实例纠正了我使用 .NET Core API 和 HTTPRequest (Request.Body) 的方法。这也让我意识到我正在使用Load() 方法并且应该一直使用LoadXml() 方法。谢谢。
【解决方案2】:

您应该将 XML 阅读器输入存储在字符串变量中,因为第二次调用 ReadToEnd() 方法时,它无法从流中读取任何内容,因为它已经在末尾并返回一个空字符串。

string responseString = response.ReadToEnd()

【讨论】:

    【解决方案3】:

    当你打电话时 Console.WriteLine(response.ReadToEnd()); 它会在第二次读取所有响应内容,您可以再次读取它

    string responsecontent=response.ReadToEnd();
    

    并在任何地方使用响应内容

    【讨论】:

      【解决方案4】:

      在反序列化时使用 deserializeRootElementName 作为“根”

      XmlDocument xmlResponse = JsonConvert.DeserializeXmlNode(response,"root");

      【讨论】:

      • 您好,欢迎来到 Stack Overflow!请拨打tour。您能否添加有关您的代码如何解决问题的解释?您可以在此help center article 中找到有关代码格式的信息。
      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多