C# 从流加载XmlDocument时缺少根元素

C# 从流加载XmlDocument时缺少根元素,c#,.net,xml,exception-handling,C#,.net,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 na

我有以下代码:

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);
      }
  }
我得到:

缺少根元素

地址:

我的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>
致:


如果没有它,这将无法工作。

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

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

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

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

string responsecontent=response.ReadToEnd();

并在反序列化时使用responsecontent anywhere

将反序列化ZerooteElementName用作“根”


XmlDocument xmlResponse=JsonConvert.DeserializeXmlNode(响应,“根”)

Console.WriteLine(response.ReadToEnd())的作用是什么;产出?你如何期望蒸汽能带来“实质性”的产出(对不起,忍不住…)比我快24秒,我想我必须提高我的打字速度:)太好了!泰!这让我越过了那条线!我现在在nodepath行中看到了这一点:需要名称空间管理器或XsltContext。此查询具有前缀、变量或用户定义的函数。@ErocM,注释不适合询问或回答问题。你应该问一个全新的问题。很好!这帮助我通过
StreamReader
类的一个实例,在
using
语句中使用.NET核心API和
HTTPRequest
Request.Body
)来纠正我的方法。这也让我意识到我使用的是
Load()
方法,应该使用
LoadXml()
方法。谢谢。嗨,欢迎来到Stack Overflow!请坐飞机。你能解释一下你的代码是如何解决这个问题的吗?您可以在此中找到有关代码格式的信息。
string responseString = response.ReadToEnd();
…
Console.WriteLine(reponseString);
…
XmlDoc.LoadXml(responseString);
string responseString = response.ReadToEnd()
string responsecontent=response.ReadToEnd();