c# - XML Error: There are multiple root elements -


i getting xml web service. here xml looks like:

<parent>     <child>         text     </child> </parent> <parent>     <child>         <grandchild>             text         </grandchild>         <grandchild>             text         </grandchild>     </child>     <child>         text     </child> </parent>  etc. 

and here c# code:

stringbuilder output = new stringbuilder();  // create xmlreader using (xmlreader reader = xmlreader.create(new stringreader(xoresponse.@return))) {     xmlwritersettings ws = new xmlwritersettings();     //ws.indent = true;     using (xmlwriter writer = xmlwriter.create(output, ws))     {         // parse file , display each of nodes.         while (reader.read())         {             switch (reader.nodetype)             {                 case xmlnodetype.element:                     writer.writestartelement(reader.name);                     break;                 case xmlnodetype.text:                     writer.writestring(reader.value);                     break;                 case xmlnodetype.xmldeclaration:                 case xmlnodetype.processinginstruction:                     writer.writeprocessinginstruction(reader.name, reader.value);                     break;                 case xmlnodetype.comment:                     writer.writecomment(reader.value);                     break;                 case xmlnodetype.endelement:                     writer.writefullendelement();                     break;             }         }     } } 

i believe error thrown on second parent element. how can avoid error? appreciated.

you need enclose <parent> elements in surrounding element xml documents can have 1 root node:

<parents> <!-- i've added tag -->     <parent>         <child>             text         </child>     </parent>     <parent>         <child>             <grandchild>                 text             </grandchild>             <grandchild>                 text             </grandchild>         </child>         <child>             text         </child>     </parent> <parents> <!-- i've added tag --> 

as you're receiving markup somewhere else, rather generating yourself, may have treating response string , wrapping appropriate tags, prior attempting parse xml.

so, you've couple of choices:

  1. get provider of web service return actual xml has 1 root node
  2. pre-process xml, i've suggested above, add root node
  3. pre-process xml split multiple chunks (i.e. 1 each <parent> node) , process each distinct xml document

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -