简体   繁体   中英

Root element is missing when load XmlDocument from a stream

I have the following code:

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);
      }
  }

I am getting:

Root element is missing.

at:

XmlDoc.LoadXml(response.ReadToEnd());

My XML looks like this:

<?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>

I'm lost. Can someone tell me what I'm doing wrong? I know I had this working before so I'm not sure what I screwed up.

As always, thanks!

* Reason for my edit after I got my answer * *

I needed to change the line:

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

to:

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

This will not work without it.

It seems you're reading the response stream twice. It doesn't work that way, you get an empty string the second time. Either remove the line Console.WriteLine(response.ReadToEnd()); or save the response to a string:

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

You should store the XML readers input in a string variable, since the second time the ReadToEnd() method is being called, it can not read anything from the stream, as it is already at the end and returns an empty string.

string responseString = response.ReadToEnd()

when you call Console.WriteLine(response.ReadToEnd()); it reads all responde content at second time you can read it agiin

string responsecontent=response.ReadToEnd();

and use responsecontent anywhere

while deserializing use deserializeRootElementName as "root"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM