Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 650
ErocM Avatar asked Jul 05 '11 14:07

ErocM


1 Answers

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);
like image 165
svick Avatar answered Sep 19 '22 16:09

svick