从流中加载XmlDocument时缺少根元素

Ero*_*ocM 7 .net c# xml exception-handling

我有以下代码:

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);
      }
  }
Run Code Online (Sandbox Code Playgroud)

我正进入(状态:

根元素缺失.

在:

XmlDoc.LoadXml(response.ReadToEnd());
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

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

一如既往,谢谢!

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

我需要改变这条线:

XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response");
Run Code Online (Sandbox Code Playgroud)

至:

XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response", mgr);
Run Code Online (Sandbox Code Playgroud)

没有它,这将无法运作.

svi*_*ick 14

看来你正在读response两次流.它不起作用,你第二次得到一个空字符串.删除该行Console.WriteLine(response.ReadToEnd());或将响应保存到字符串:

string responseString = response.ReadToEnd();
…
Console.WriteLine(reponseString);
…
XmlDoc.LoadXml(responseString);
Run Code Online (Sandbox Code Playgroud)