0

How to parse single xml node in Windows Phone, I have described my web service result in code:

    void abcd_Completed(object sender, ServiceReference1.abcdCompletedEventArgs e)
    {
       Xdocument doc = XDocument.Parse(e.Result);
    }

my e.Result is

<root>1234</root>

if I run this code in emulator, I am getting the result but in device it returns error like this:

"Data at Root level is invalid"

how to solve this..I am stuck here.Thanks!!

Viraj Shah
  • 308
  • 1
  • 12
  • That may be caused by a wrong structure of your xml file. First question(stupid), does your xml file has the node? – Olter Apr 02 '14 at 05:26
  • @Olter no, my xml file has not , I think it takes as a string, so how to read string? – Viraj Shah Apr 02 '14 at 05:41
  • It takes a string, right. But if you use a XDocument class, you should also check, if the given string satisfies rules for xml file structure. Otherwise, it will throw an error. – Olter Apr 02 '14 at 05:53
  • @Olter how do I parse that string, can you show me? – Viraj Shah Apr 02 '14 at 06:01
  • 1
    You XML-parsing is correct. The problem is not with your parsing method, but with your XML file, which has wrong structure. Your web service is giving you the file, which IS NOT a correct XML-file. So, you should check the web service, the problem is in there. Got it? – Olter Apr 02 '14 at 06:05
  • @Olter Ok, I understand,thanks brother, but is there any other way to handle that string by my side, because I am not creating web service, I just call the method.So – Viraj Shah Apr 02 '14 at 06:17
  • @VirajShah, please add to question 1) Your **whole** xml file, you want to be parsed. 2) The result, you want to receive. – Olter Apr 02 '14 at 06:44
  • @Olter in my question, e.Result is my whole xml file means 1234..is my whole xml file that I am getting as a web service response – Viraj Shah Apr 02 '14 at 07:02

2 Answers2

0

Data at Root level is invalid most likely means, that xml file has invalid structure. Note, that each xml file must start with header node:

<?xml version="1.0"?>

If your xml file doesn't have this header, XDocument.Parse method would not parse this file, as an xml.

Also, here's an example at MSDN. See, how the xml file should look like.


Now, your whole file looks like this:

<root>1234</root>

It's not an XML file. XML file should look like this:

 <?xml version="1.0" encoding="UTF-8"?>
 <root>1234</root>

Then you can access the root value:

string root = doc.Descendants("root").FirstOrDefault().Value;
Olter
  • 1,129
  • 1
  • 21
  • 40
0

If you need to parse a XML node you should use XElement.Parse instead of the XDocument.Parse

But your case is the invalid close tag in your XML code, the <root> node has not been closed because the second <root> is the next open tag, you should change it to </root>

Correct XML is: <root>1234</root>

Viacheslav Smityukh
  • 5,652
  • 4
  • 24
  • 42